<?php
//include_once dirname(dirname(__FILE__)).'/jllt_client.php';
include_once dirname(__FILE__).'/public_model_exec.class.php';
/**
 * 
调用本类注入方法时，请传如下两个参数：
nns_task_id
nns_task_name
参数传值分三种情况：
categogy操作时：
nns_task_id  ： 分类名称
nns_task_name   ：sp分类id

c2_task操作（vod，index）：
nns_task_id  ： c2_task 的nns_id
nns_task_name   ：vod或者index名称

片源操作：（片源注入时都以分集为单位）
nns_task_id  ： 切片任务id
nns_task_name   ：分集名称
 * 
 */
class c2_task_model
{
	static public function get_BizDomain($sp_id)
	{
		if($sp_id=='hndx' || $sp_id=='hnlt_zx' || $sp_id=='hndx_hw')
		{
			return 520;
		}
		elseif($sp_id=='xjcbc_dx_hw' || $sp_id=='xjdx_hw' || $sp_id=='cbczq_hw' || $sp_id=='cqyx' || $sp_id=='cqyx_hw')
		{
			return 0;
		}
		elseif($sp_id=='xjcbc_dx_zte' || $sp_id=='xjdx_zte' || $sp_id=='cbczq_zte' )
		{
			return 257;
		}
		if ($sp_id == 'hljdx_hw')
        {
            return 0;
        }
		else
		{
			return 2;
		}
	}

	static public function add_new_maping($item,$xml_str,$sp_id){
		$action='REGIST';
		//$item = array();
		//$item['nns_task_name'] = $title."-".$start_time."-[节目单]";

		$time = date('YmdHis') . rand(0, 10000);
		$three_rand = rand(100, 999);
		$file_name = 'zgcms_'. $time .'_' . 'maping' .'_'. $action . '_' . $three_rand. '.xml';

		$c2_info = array();
		$c2_info['c2_id'] = np_guid_rand();
		$c2_info['file_name'] = $file_name;
		$c2_info['xml_content'] = $xml_str;
		$c2_info = array(
			'nns_task_type'=>'Maping',
			'nns_task_id'=> null,
			'nns_task_name'=> isset($item['nns_task_name'])?$item['nns_task_name']:null,
			'nns_action'=>	$action,
			'nns_url' => $file_name,
			'nns_content' => $xml_str,
			'nns_desc' => 'Maping,'.$action,
		);
		//return self::execute_c2($c2_info,$sp_id);
	}

	static public function add_new_playbill($live_id,$xml_str,$start_time,$sp_id){
		$db = nn_get_db(NL_DB_READ);
		$action = 'REGIST';
		$sql="select nns_name from nns_live where nns_id='$live_id'";		
		$title = nl_db_get_col($sql, $db);
		$item = array();
		$item['nns_task_name'] = $title."-".$start_time."-[节目单]";

		$time = date('YmdHis') . rand(0, 10000);
		$three_rand = rand(100, 999);
		$file_name = 'zgcms_'. $time .'_' . 'schedule' .'_'. $action . '_' . $three_rand. '.xml';

		$c2_info = array();
		$c2_info['c2_id'] = np_guid_rand();
		$c2_info['file_name'] = $file_name;
		$c2_info['xml_content'] = $xml_str;
		$c2_info = array(
			//'nns_id' => $c2_info['c2_id'],
			'nns_task_type'=>'Schedule',
			'nns_task_id'=> np_guid_rand(),	
			'nns_task_name'=> isset($item['nns_task_name'])?$item['nns_task_name']:null,
			'nns_action'=>	$action,
			'nns_url' => $file_name,
			'nns_content' => $xml_str,
			//'nns_result' =>$result,
			'nns_desc' => 'Schedule,'.$action,
		);
		return self::execute_c2($c2_info,$sp_id);
		
	}

	static public function do_package($package,$action,$sp_id){
		$package_num='';

		if($package=='VOD'){
			$package_num=0;
		}
		else if($package=='Channel')
		{
			$package_num=2;
		}
		else if($package=='TVOD')
		{
			$package_num=3;
		}
		else if($package=='SVOD')
		{
			$package_num=4;
		}
		else if($package=='PVOD')
		{
			$package_num=5;
		}

		$BizDomain = self::get_BizDomain($sp_id);
		$xml_str = '<?xml version="1.0" encoding="UTF-8"?><ADI xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" BizDomain="'.$BizDomain.'" Priority="1">';
		$xml_str .= '<Objects>';
		$xml_str .= '<Object ElementType="Package" ID="' .$package. '" Action="' . $action . '" Code="' .$package. '">';
		$xml_str .= '<Property Name="Name">'.$package.'</Property>';
		$xml_str .= '<Property Name="Type">'.$package_num.'</Property>';
		$xml_str .= '<Property Name="OrderNumber">'.$package.'</Property>';
		$xml_str .= '<Property Name="LicensingWindowStart">20140101000000</Property>';
		$xml_str .= '<Property Name="LicensingWindowEnd">20540101000000</Property>';
		$xml_str .= '<Property Name="Price">1.00</Property>';
		$xml_str .= '<Property Name="Status">1</Property>';
		$xml_str .= '</Object>';
		$xml_str .= '</Objects>';
		$xml_str .= '</ADI>';

		//zgcms_时间_媒资类型_动作_3位随机数.xml
		$time = date('YmdHis') . rand(0, 10000);
		$three_rand = rand(100, 999);
		$file_name = 'zgcms_'. $time .'_' . strtolower($package) .'_'. $action . '_' . $three_rand. '.xml';

		$c2_info = array(
		'nns_task_type'=>'Package',
		'nns_task_id'=> $package,
		'nns_task_name'=> $package,
		'nns_action'=> $action,
		'nns_url' =>$file_name,
		'nns_content' => $xml_str,
		'nns_desc' => 'Package,'.$action,
		);

		return  self::execute_c2($c2_info,$sp_id);
	}

	/**
	 * 添加内容栏目
	 */
	static public function add_categoy($category_info,$sp_id){
		if(file_exists(dirname(dirname(__FILE__)).'/'.$sp_id.'/models/child_c2_task_model.php')){
			include_once dirname(dirname(__FILE__)).'/'.$sp_id.'/models/child_c2_task_model.php';
			if(method_exists('child_c2_task_model','add_categoy')){
				$re = child_c2_task_model::add_categoy($category_info,$sp_id);
				return $re;
			}
		}
		$action = 'REGIST';
		return self::do_category($category_info,$action,$sp_id);
	}
	/**
	 * 添加内容栏目
	 */	
	static public function update_category($category_info,$sp_id){
		if(file_exists(dirname(dirname(__FILE__)).'/'.$sp_id.'/models/child_c2_task_model.php')){
			include_once dirname(dirname(__FILE__)).'/'.$sp_id.'/models/child_c2_task_model.php';
			if(method_exists('child_c2_task_model','update_category')){
				$re = child_c2_task_model::update_category($category_info,$sp_id);
				return $re;
			}
		}
		$action = 'UPDATE';
		return self::do_category($category_info,$action,$sp_id);
	}
	/**
	 * $param array(
	 * nns_id
	 * nns_task_id
	 * )
	 */
	static public function delete_category($param,$sp_id){
		
		if(file_exists(dirname(dirname(__FILE__)).'/'.$sp_id.'/models/child_c2_task_model.php')){
			include_once dirname(dirname(__FILE__)).'/'.$sp_id.'/models/child_c2_task_model.php';
			if(method_exists('child_c2_task_model','delete_category')){
				$re = child_c2_task_model::delete_category($param,$sp_id);
				return $re;
			}
		}
		
		$category_id = $param['nns_id'];
		$action = "DELETE";
		$BizDomain = self::get_BizDomain($sp_id);
		$xml_str = '<?xml version="1.0" encoding="UTF-8"?><ADI xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" BizDomain="'.$BizDomain.'" Priority="1">';
		$xml_str .= '<Objects>';
		$xml_str .= '<Object ElementType="Category" ID="' .$category_id. '" Action="' . $action . '" Code="' .$category_id. '">';

		$xml_str .= '</Object>';
		$xml_str .= '</Objects>';
		$xml_str .= '</ADI>';

		$time = date('YmdHis') . rand(0, 10000);
		$three_rand = rand(100, 999);
		$file_name = 'zgcms_'. $time .'_' . 'category' .'_'. $action . '_' . $three_rand. '.xml';

		
		$c2_info = array(
		'nns_task_type'=>'Category',
		'nns_task_id'=> isset($param['nns_task_id'])?$param['nns_task_id']:null,
		'nns_task_name'=> isset($param['nns_task_name'])?$param['nns_task_name']:null,
		'nns_action'=>	$action,
		'nns_url' =>$file_name,
		'nns_content' => $xml_str,
		'nns_desc' => 'Category,'.$action,
		);		
		return  self::execute_c2($c2_info,$sp_id);

		/*
		self::save_c2_log($c2_log);
		if($result['ret']==0){
			return true;
		}else{
			return false;
		}*/		
	}
	/**
	 * 内容栏目
	 * $category_info array(
	 * 'nns_category_id'
	 * 'nns_parent_id'
	 * 'nns_name'
	 * )
	 */
	static public function do_category($category_info,$action,$sp_id){
		$sort = empty($category_info['nns_sort'])?0:$category_info['nns_sort'];
		$BizDomain = self::get_BizDomain($sp_id);
		$xml_str = '<?xml version="1.0" encoding="UTF-8"?><ADI xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" BizDomain="'.$BizDomain.'" Priority="1">';
		$xml_str .= '<Objects>';
		$xml_str .= '<Object ElementType="Category" ID="' .$category_info['nns_category_id']. '" Action="' . $action . '" Code="' .$category_info['nns_category_id']. '" ParentCode="'.$category_info['nns_parent_id'].'">';
		$xml_str .= '<Property Name="Name">'.$category_info['nns_name'].'</Property>';
		$xml_str .= '<Property Name="ParentID">'.$category_info['nns_parent_id'].'</Property>';
		$xml_str .= '<Property Name="Sequence">'.$sort.'</Property>';
		$xml_str .= '<Property Name="Status">1</Property>';
		$xml_str .= '<Property Name="Description"></Property>';
		$xml_str .= '</Object>';
		$xml_str .= '</Objects>';
		$xml_str .= '</ADI>';

		$time = date('YmdHis') . rand(0, 10000);
		$three_rand = rand(100, 999);
		$file_name = 'zgcms_'. $time .'_' . 'category' .'_'. $action . '_' . $three_rand. '.xml';

		
		$c2_info = array(
		'nns_task_type'=>'Category',
		'nns_task_id'=> isset($category_info['nns_task_id'])?$category_info['nns_task_id']:null,
		'nns_task_name'=> isset($category_info['nns_task_name'])?$category_info['nns_task_name']:null,
		'nns_action'=>	$action,
		'nns_url' => $file_name,
		'nns_content' => $xml_str,

		'nns_desc' => 'Category,'.$action,
		);		
		return self::execute_c2($c2_info,$sp_id);
	}
	/**
	 * 本方法可用于测试，不建议其他地方使用
	 */
	static public function delete_series_by_ids($params){
		$action = "DELETE";
		
		$xml_str = '<?xml version="1.0" encoding="UTF-8"?><ADI xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" BizDomain="2" Priority="1">';
		$xml_str .= '<Objects>';
		foreach($params['nns_ids'] as $id){
			$xml_str .= '<Object ElementType="Series" ID="' .$id. '" Action="' . $action . '" Code="' .$id. '">';
			$xml_str .= '</Object>';
		}
		
		$xml_str .= '</Objects>';
		$xml_str .= '</ADI>';

		$guid = np_guid_rand();
		$time = date('YmdHis') . rand(0, 10000);
		$three_rand = rand(100, 999);
		$file_name = 'zgcms_'. $time .'_' . 'series' .'_'. $action . '_' . $three_rand. '.xml';

		$c2_info = array(
		//'nns_id' => $c2_info['c2_id'],
		'nns_task_type'=>'Series',
		'nns_task_id'=>  isset($params['nns_task_id'])?$params['nns_task_id']:null,	
		'nns_task_name'=>  isset($params['nns_task_name'])?$params['nns_task_name']:null,	
		'nns_action'=>	$action,		
		'nns_url' => $file_name,
		'nns_content' => $xml_str,
		//'nns_result' => '['.$result['ret'].']'.$result['desc'],
		'nns_desc' => 'Series,'.$action,
		);		
		
		return self::execute_c2($c2_info);

	}	
	/**
	 * @params array(
	 * nns_id
	 * nns_task_id
	 * )
	 */
	static public function delete_series($params,$sp_id){
		include_once dirname(dirname(__FILE__)).'/'.$sp_id.'/define.php';
		
		
		$sp_config = sp_model::get_sp_config($sp_id);
		if(isset($sp_config['c2_import_cdn_model']) && $sp_config['c2_import_cdn_model'] !=0 )
		{
		    include_once dirname(__FILE__).'/child_models/c2_task_assign.class.php';
		    $obj_c2_task_assign = new c2_task_assign();
		    $result_c2_task_assign = $obj_c2_task_assign->auto_load_task_model($sp_config['c2_import_cdn_model'], 'do_video',null,$sp_id,$sp_config,$params);
		    if($result_c2_task_assign['ret'] !=2)
		    {
		        return ($result_c2_task_assign['ret'] == 0) ? true : false;
		    }
		}
		
		
		if(file_exists(dirname(dirname(__FILE__)).'/'.$sp_id.'/models/child_c2_task_model.php')){
			include_once dirname(dirname(__FILE__)).'/'.$sp_id.'/models/child_c2_task_model.php';
			if(method_exists('child_c2_task_model','delete_series')){
				$re = child_c2_task_model::delete_series($params,$sp_id);
				return $re;
			}
		}
		
		$sp_config = sp_model::get_sp_config($sp_id);
		if(isset($sp_config['import_id_mode'])&&strlen($sp_config['import_id_mode'])>0&&(int)$sp_config['import_id_mode']>0){
			$video_info = video_model::get_vod_info($params['nns_id']);
			switch ($sp_config['import_id_mode']) {
				case '1':
				    if ($sp_id == 'hndx')
                    {
                        $params['nns_id'] = '001000'.$video_info['nns_integer_id'];
                        $params['nns_id'] = str_pad($params['nns_id'],32,"0");
                    }
					else
                    {
                        $params['nns_id'] = '000000'.$video_info['nns_integer_id'];
                        $params['nns_id'] = str_pad($params['nns_id'],32,"0");
                    }
					break;
				case '2':
					$params['nns_id'] = $video_info['nns_asset_import_id'];
					break;
				case '3':
					$params['nns_id'] = CSP_ID . '0000' . $video_info['nns_integer_id'];
					$params['nns_id'] = str_pad($params['nns_id'],32,"0");
					break;
				case '4':
					$arr_csp_id = explode("|", CSP_ID);
					$str_lenth = strlen($arr_csp_id[0])+strlen($arr_csp_id[1])+1;
					$lest_num = 32-$str_lenth;
					$params['nns_id'] = $arr_csp_id[0].'1'.str_pad($video_info['nns_integer_id'], $lest_num, "0", STR_PAD_LEFT).$arr_csp_id[1];
					break;
			}
		}
		
		$action = "DELETE";
		$BizDomain = self::get_BizDomain($sp_id);
		$xml_str = '<?xml version="1.0" encoding="UTF-8"?><ADI xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" BizDomain="'.$BizDomain.'" Priority="1">';
		$xml_str .= '<Objects>';
		$xml_str .= '<Object ElementType="Series" ID="' .$params['nns_id']. '" Action="' . $action . '" Code="' .$params['nns_id']. '">';

		$xml_str .= '</Object>';
		$xml_str .= '</Objects>';
		$xml_str .= '</ADI>';

		$time = date('YmdHis') . rand(0, 10000);
		$three_rand = rand(100, 999);
		$file_name = 'zgcms_'. $time .'_' . 'series' .'_'. $action . '_' . $three_rand. '.xml';

		$c2_info = array(
		'nns_task_type'=>'Series',
		'nns_task_id'=> isset($params['nns_task_id'])?$params['nns_task_id']:null,
		'nns_task_name'=> isset($params['nns_task_name'])?$params['nns_task_name']:null,
		'nns_action'=> $action,
		'nns_url' => $file_name,
		'nns_content' => $xml_str,
		'nns_desc' => 'Series,'.$action,
		);
		return self::execute_c2($c2_info,$sp_id);

	}
	
	
	
	//如果没有收缩到任务名称
	
	 static public function get_task_name($task_id){
	 	$db = nn_get_db(NL_DB_READ);
		$sql = "select nns_name from nns_mgtvbk_c2_task where nns_id='$task_id'";
		return nl_db_get_col($sql, $db);
	 }

	//修改连续剧
	static public function update_series($vod_info,$sp_id){
		
		if(file_exists(dirname(dirname(__FILE__)).'/'.$sp_id.'/models/child_c2_task_model.php')){
			include_once dirname(dirname(__FILE__)).'/'.$sp_id.'/models/child_c2_task_model.php';
			if(method_exists('child_c2_task_model','update_series')){
				$re = child_c2_task_model::update_series($vod_info,$sp_id);
				return $re;
			}
		}
		
		$action = 'UPDATE';
		return self::do_series($vod_info,$action,$sp_id);
	}

	//添加连续剧
	static public function add_series($vod_info,$sp_id){
		
		if(file_exists(dirname(dirname(__FILE__)).'/'.$sp_id.'/models/child_c2_task_model.php')){
			include_once dirname(dirname(__FILE__)).'/'.$sp_id.'/models/child_c2_task_model.php';
			if(method_exists('child_c2_task_model','add_series')){
				$re = child_c2_task_model::add_series($vod_info,$sp_id);
				return $re;
			}
		}
		
		$action = 'REGIST';
		return self::do_series($vod_info,$action,$sp_id);
	}

	//连续剧
	static public function do_series($vod_info,$action,$sp_id)
    {

        $vod_id = $vod_info['nns_id'];

        $program_id = $vod_id;
        include dirname(dirname(__FILE__)) . '/' . $sp_id . '/define.php';

        if (empty($vod_info['nns_task_name'])) {
            $vod_info['nns_task_name'] = self::get_task_name($vod_info['nns_task_id']);
        }
        if (empty($vod_info['nns_name'])) {
            $vod_info['nns_name'] = $vod_info['nns_task_name'];
        }

        /**
         * 如果总集数为-1，注入CDN时将总集数设置为1
         * @author chunyang.shu
         * @date 2018-02-08
         */
        if ($vod_info['nns_all_index'] == -1)
        {
            $vod_info['nns_all_index'] = 1;
        }

		$BizDomain = self::get_BizDomain($sp_id);
		$xml_str = '<?xml version="1.0" encoding="UTF-8"?><ADI xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" BizDomain="'.$BizDomain.'" Priority="1">';
		$xml_str .= '<Objects>';

		$sp_config = sp_model::get_sp_config($sp_id);
		if(isset($sp_config['import_id_mode'])&&strlen($sp_config['import_id_mode'])>0&&(int)$sp_config['import_id_mode']>0){
			$video_info = video_model::get_vod_info($program_id);
			switch ($sp_config['import_id_mode']) {
				case '1':
				    if ($sp_id == 'hndx')
                    {
                        $vod_id = '001000'.$video_info['nns_integer_id'];
                        $vod_id = str_pad($vod_id,32,"0");
                    }
					else
                    {
                        $vod_id = '000000'.$video_info['nns_integer_id'];
                        $vod_id = str_pad($vod_id,32,"0");
                    }
					break;
				case '2':
					$vod_id = $video_info['nns_asset_import_id'];
					break;
				case '3':
					$vod_id = CSP_ID . '0000' . $video_info['nns_integer_id'];
					$vod_id = str_pad($vod_id,32,"0");
					break;
				case '4':
					$arr_csp_id = explode("|", CSP_ID);
					$str_lenth = strlen($arr_csp_id[0])+strlen($arr_csp_id[1])+1;
					$lest_num = 32-$str_lenth;
					$vod_id = $arr_csp_id[0].'1'.str_pad($video_info['nns_integer_id'], $lest_num, "0", STR_PAD_LEFT).$arr_csp_id[1];
					break;
			}
			
		}
		$temp_program_id = $vod_id;
		$xml_str .= '<Object ElementType="Series" ID="' .$vod_id. '" Action="' . $action . '" Code="' .$vod_id. '">';

		//到中兴或者华为name为别名
		if ($sp_id == 'xjcbc_dx_hw' || $sp_id == 'xjcbc_dx_zte' || $sp_id == 'xjdx_hw' || $sp_id == 'xjdx_zte' || $sp_id=='cbczq_hw'  || $sp_id=='cbczq_zte')
		{
		    $vod_info['nns_alias_name']  = strlen($vod_info['nns_alias_name']) <1 ? $vod_info['nns_name'] : $vod_info['nns_alias_name'];
// 			$xml_str .= '<Property Name="Name">'.htmlspecialchars($vod_info['nns_alias_name'],ENT_QUOTES).'</Property>';
			$xml_str .= '<Property Name="Name">'.htmlspecialchars(mb_substr($vod_info['nns_alias_name'],0,32,'utf-8'),ENT_QUOTES).'</Property>';
		}
		else
		{
			$xml_str .= '<Property Name="Name">'.htmlspecialchars($vod_info['nns_name'],ENT_QUOTES).'</Property>';
		}

		$xml_str .= '<Property Name="OrderNumber"></Property>';//节目订购编号
		$xml_str .= '<Property Name="OriginalName">'.htmlspecialchars(mb_substr($vod_info['nns_alias_name'],0,32,'utf-8'),ENT_QUOTES).'</Property>';//原名
		$xml_str .= '<Property Name="SortName"></Property>';//索引名称供界面排序
		$xml_str .= '<Property Name="SearchName">'.$vod_info['nns_pinyin'].'</Property>';//搜索名称供界面搜索
		
		$str_date = ($vod_info['nns_show_time'] == '0000-00-00' || empty($vod_info['nns_show_time'])) ? date('Ymd') : date('Ymd',strtotime($vod_info['nns_show_time']));
		$xml_str .= '<Property Name="OrgAirDate">' . $str_date .'</Property>';//首播日期(YYYYMMDD)
		$xml_str .= '<Property Name="LicensingWindowStart">'. date('YmdHis').'</Property>';//有效开始时间(YYYYMMDDHH24MiSS)
		$xml_str .= '<Property Name="LicensingWindowEnd">'. date('YmdHis',time()+ 3*365*24*60*60).'</Property>';//有效结束时间(YYYYMMDDHH24MiSS)		
		$xml_str .= '<Property Name="DisplayAsNew">0</Property>';//新到天数
		$xml_str .= '<Property Name="DisplayAsLastChance">300</Property>';//剩余天数
		$xml_str .= '<Property Name="Macrovision">0</Property>';//拷贝保护标志0:无拷贝保护	1:有拷贝保护
		$xml_str .= '<Property Name="Price">0</Property>';//含税定价
		$xml_str .= '<Property Name="VolumnCount">'.$vod_info['nns_all_index'].'</Property>';//总集数
		$xml_str .= '<Property Name="Status">1</Property>';//状态标志,0:失效 1:生效
		if($sp_id =='xjcbc_dx_zte' || $sp_id =='xjdx_zte'  || $sp_id=='cbczq_zte')
		{
			$xml_str .= '<Property Name="Description">'.htmlspecialchars(mb_substr($vod_info['nns_summary'],0,256,'utf-8'),ENT_QUOTES).'</Property>';//描述信息
		}
		elseif ($sp_id=='cqyx')
		{
		    $xml_str .= '<Property Name="Description">'.htmlspecialchars(mb_substr($vod_info['nns_summary'],0,128,'utf-8'),ENT_QUOTES).'</Property>';//描述信息
		}
		else
		{
            $xml_str .= '<Property Name="Description">'.htmlspecialchars(mb_substr($vod_info['nns_summary'],0,128,'utf-8'),ENT_QUOTES).'</Property>';//描述信息
		}
		if($sp_id =='xjcbc_dx_zte' || $sp_id =='xjdx_zte'  || $sp_id=='cbczq_zte')
		{
			$xml_str .= '<Property Name="Type">MV</Property>';//演职角色名称
		}
		else
		{
			if(empty($vod_info['nns_kind']))
			{
				$vod_info['nns_kind'] = $vod_info['nns_keyword'];
			}
			$xml_str .= '<Property Name="Type">'.htmlspecialchars($vod_info['nns_kind'],ENT_QUOTES).'</Property>';//节目内容类型,字符串，表示内容类型，例如：电影，连续剧，新闻，体育…
		}
// 		$xml_str .= '<Property Name="Type">'.htmlspecialchars($vod_info['nns_kind'],ENT_QUOTES).'</Property>';//节目内容类型,字符串，表示内容类型，例如：电影，连续剧，新闻，体育…
		if ($sp_id=='cqyx')
		{
		    $xml_str .= '<Property Name="Keywords">'.htmlspecialchars(mb_substr($vod_info['nns_keyword'],0,32,'utf-8'),ENT_QUOTES).'</Property>';//关键字
		}
		else
		{
            $xml_str .= '<Property Name="Keywords">'.htmlspecialchars(mb_substr($vod_info['nns_keyword'],0,32,'utf-8'),ENT_QUOTES).'</Property>';//关键字
		}
		$xml_str .= '<Property Name="Tags">0</Property>';//关联标签
		$xml_str .= '<Property Name="Reserve1"></Property>';//保留字段
		$xml_str .= '<Property Name="Reserve2"></Property>';//保留字段
		$xml_str .= '<Property Name="Reserve3"></Property>';//保留字段
		$xml_str .= '<Property Name="Reserve4"></Property>';//保留字段
		$xml_str .= '<Property Name="Reserve5"></Property>';//保留字段
		if($sp_id!='hndx' && $sp_id!='hnlt_zx' && $sp_id!='hndx_hw' && $sp_id!='xjcbc_dx_hw' && $sp_id!='xjcbc_dx_zte' && $sp_id!='xjdx_hw' && $sp_id!='cbczq_hw' && $sp_id!='xjdx_zte' && $sp_id!='cbczq_zte' && $sp_id!='cqyx' && $sp_id!='cqyx_hw')
		{
			$xml_str .= '<Property Name="RMediaCode"></Property>';//关联内容唯一标识 ,为了支持表示不同屏的同一个内容关系		
		}
		$xml_str .= '</Object>';
		
		if($sp_id!='hndx' && $sp_id!='hnlt_zx' && $sp_id!='hndx_hw' && $sp_id!='xjcbc_dx_hw' && $sp_id!='xjcbc_dx_zte' && $sp_id!='xjdx_hw' && $sp_id!='cbczq_hw' && $sp_id!='xjdx_zte' && $sp_id!='cbczq_zte' && $sp_id!='cqyx' && $sp_id!='cqyx_hw' && $sp_id != 'hljdx')
		{
			//演员
			$db = nn_get_db(NL_DB_READ);
			//$db->open();
			$sql = "select l.* from nns_video_label l ,nns_video_label_bind_1006 b where l.nns_id=b.nns_label_id and b.nns_video_id='".$program_id."' ";
			$yy_result = nl_db_get_all($sql,$db);
			if(is_array($yy_result)){
				foreach($yy_result as $label){
					$cast_name = $label['nns_name'];
					$first_name = $label['nns_name'];
					if(strlen($label['nns_name']) > 64){
						$cast_name = i_substr($label['nns_name'],30);
					}
					if(strlen($label['nns_name']) > 32){
						$first_name = i_substr($label['nns_name'],30);
					}
					$xml_str .= '<Object ElementType="Cast" ID="' .$label['nns_id']. '" Action="REGIST" Code="' .$label['nns_id']. '">';
					$xml_str .= '<Property Name="Name">'.$cast_name.'</Property>';//
					$xml_str .= '<Property Name="FirstName">'.$first_name.'</Property>';//
					$xml_str .= '</Object>';

					//我方没有演员角色关系表，这里将角色的id设置为 演员标签id+节目id，角色名称设为演员名
					$xml_str .= '<Object ElementType="CastRoleMap" ID="' .$label['nns_id'].$program_id. '" Action="REGIST" Code="' .$label['nns_id'].$program_id. '">';
					$xml_str .= '<Property Name="CastRole">演员</Property>';//演职角色名称
					$xml_str .= '<Property Name="CastID">'.$label['nns_id'].'</Property>';//人物ID
					$xml_str .= '<Property Name="CastCode">'.$label['nns_id'].'</Property>';//人物Code
					$xml_str .= '</Object>';
					
				}
			}
			//导演
			$sql = "select l.* from nns_video_label l ,nns_video_label_bind_1005 b where l.nns_id=b.nns_label_id and b.nns_video_id='".$program_id."' ";
			$dy_result = nl_db_get_all($sql,$db);
			if(is_array($dy_result)){
				foreach($dy_result as $label){
					$cast_name = $label['nns_name'];
					$first_name = $label['nns_name'];
					if(strlen($label['nns_name']) > 64){
						$cast_name = i_substr($label['nns_name'],30);
					}
					if(strlen($label['nns_name']) > 32){
						$first_name = i_substr($label['nns_name'],30);
					}
					$xml_str .= '<Object ElementType="Cast" ID="' .$label['nns_id']. '" Action="REGIST" Code="' .$label['nns_id']. '">';
					$xml_str .= '<Property Name="Name">'.htmlspecialchars($cast_name,ENT_QUOTES).'</Property>';//
					$xml_str .= '<Property Name="FirstName">'.htmlspecialchars($first_name,ENT_QUOTES).'</Property>';//
					$xml_str .= '</Object>';

					//我方没有演员角色关系表，这里将角色的id设置为 演员标签id+节目id，角色名称设为演员名
					$xml_str .= '<Object ElementType="CastRoleMap" ID="' .$label['nns_id'].$program_id. '" Action="REGIST" Code="' .$label['nns_id'].$program_id. '">';
					$xml_str .= '<Property Name="CastRole">导演</Property>';//演职角色名称
					$xml_str .= '<Property Name="CastID">'.$label['nns_id'].'</Property>';//人物ID
					$xml_str .= '<Property Name="CastCode">'.$label['nns_id'].'</Property>';//人物Code
					$xml_str .= '</Object>';
					
				}
			}		

			//图片
			/*if(!empty($vod_info['nns_image0'])){
				$img_save_name = str_replace('.JPG','.jpg',$vod_info['nns_image0']);
				$pic_url = self::get_image_url($img_save_name,$sp_id);
				$xml_str .= '<Object ElementType="Picture" ID="' .$program_id.'_image0'. '" Action="' . $action . '" Code="' .$program_id.'_image0'. '">';
				$xml_str .= '<Property Name="FileURL">'.$pic_url.'</Property>';//图片文件URL, 此路径格式支持ftp、http两种方式
				$xml_str .= '<Property Name="Description"></Property>';//描述
				$xml_str .= '</Object>';
			}*/
			if(!empty($vod_info['nns_image2'])){
				if($action=='REGIST'){
					$img_save_name = str_replace('.JPG','.jpg',$vod_info['nns_image2']);
					$file_img = dirname(dirname(dirname(__FILE__))).'/data/downimg/'.$img_save_name;
					if(file_exists($file_img)){
						$pic_url = self::get_image_url($img_save_name,$sp_id);
						$xml_str .= '<Object ElementType="Picture" ID="' .$program_id.'_image2'. '" Action="' . $action . '" Code="' .$program_id.'_image2'. '">';
						$xml_str .= '<Property Name="FileURL">'.$pic_url.'</Property>';//图片文件URL, 此路径格式支持ftp、http两种方式
						$xml_str .= '<Property Name="Description"></Property>';//描述			
						$xml_str .= '</Object>';
					}
				}
				
			}
		}
		$xml_str .= '</Objects>';

		if($sp_id!='hndx' && $sp_id!='hnlt_zx' && $sp_id!='hndx_hw' && $sp_id!='xjcbc_dx_hw' && $sp_id!='xjcbc_dx_zte' && $sp_id != 'hljdx'){
		$xml_str .= '<Mappings>';
		//图片
		/*if(!empty($vod_info['nns_image0'])){
			$xml_str .= '<Mapping ParentType="Picture" ParentID="'.$program_id.'_image0'.'" ElementType="Series" ElementID="'.$program_id.'" ParentCode="'.$program_id.'_image0'.'" ElementCode="'.$program_id.'" Action="' . $action . '">';
			//Picture时：0: 缩略图 1: 海报 2: 剧照 3: 图标 4: 标题图 5: 广告图 6: 草图 7: 背景图 9: 频道图片
			//10: 频道黑白图片 11: 频道Logo 12: 频道名字图片99: 其他
			$xml_str .= '<Property Name="Type">1</Property>'; 			
			$xml_str .= '<Property Name="Sequence">0</Property>';//
			$xml_str .= '</Mapping>';
		}*/
		if($sp_id !='xjdx_hw' && $sp_id !='xjdx_zte' && $sp_id !='cbczq_hw'  && $sp_id!='cbczq_zte' && $sp_id!='cqyx' && $sp_id!='cqyx_hw')
		{
		if(!empty($vod_info['nns_image2'])){
			if($action=='REGIST'){
				$img_save_name = str_replace('.JPG','.jpg',$vod_info['nns_image2']);
				$file_img = dirname(dirname(dirname(__FILE__))).'/data/downimg/'.$img_save_name;
				if(file_exists($file_img)){
					$xml_str .= '<Mapping ParentType="Picture" ParentID="'.$program_id.'_image2'.'" ElementType="Series" ElementID="'.$vod_id.'" ParentCode="'.$program_id.'_image2'.'" ElementCode="'.$vod_id.'" Action="' . $action . '">';
					$xml_str .= '<Property Name="Type">1</Property>';
					$xml_str .= '<Property Name="Sequence">1</Property>';
					$xml_str .= '</Mapping>';
				}
			}
		}
		}

		if($sp_id == 'xjdx_zte' || $sp_id=='cbczq_zte')
		{
			$xml_str .= '<Mapping ParentType="Category" ParentID="003" ElementType="Series" ElementID="'.$temp_program_id.'" ParentCode="003" ElementCode="'.$temp_program_id.'" Action="REGIST">';
			$xml_str .= '</Mapping>';
		}
		else if($sp_id=='cqyx' || $sp_id=='cqyx_hw')
		{
			$xml_str .= '<Mapping ParentType="Category" ParentID="10000" ElementType="Series" ElementID="'.$temp_program_id.'" ParentCode="10000" ElementCode="'.$temp_program_id.'" Action="REGIST">';
			$xml_str .= '</Mapping>';
		}
		
		
		//栏目
		if(!empty($vod_info['nns_category_id'])){
			if(is_array($vod_info['nns_category_id'])){
				foreach($vod_info['nns_category_id'] as $nns_category_id){
					$xml_str .= '<Mapping ParentType="Category" ParentID="'.$nns_category_id.'" ElementType="Series" ElementID="'.$vod_id.'" ParentCode="'.$nns_category_id.'" ElementCode="'.$vod_id.'" Action="REGIST">';
					$xml_str .= '</Mapping>';
				}
			}else if(is_string($vod_info['nns_category_id'])){
				$xml_str .= '<Mapping ParentType="Category" ParentID="'.$vod_info['nns_category_id'].'" ElementType="Series" ElementID="'.$vod_id.'" ParentCode="'.$vod_info['nns_category_id'].'" ElementCode="'.$vod_id.'" Action="REGIST">';
				$xml_str .= '</Mapping>'; 
			}
		}	
		//演员
		if(is_array($yy_result)){
			foreach($yy_result as $label){
				$xml_str .= '<Mapping ParentType="Series" ParentID="'.$vod_id.'" ElementType="CastRoleMap" ElementID="'.$label['nns_id'].$program_id.'" ParentCode="'.$vod_id.'" ElementCode="'.$label['nns_id'].$program_id.'" Action="REGIST">';
				$xml_str .= '</Mapping>';
			}
		}	
		//导演
		if(is_array($dy_result)){
			foreach($dy_result as $label){
				$xml_str .= '<Mapping ParentType="Series" ParentID="'.$vod_id.'" ElementType="CastRoleMap" ElementID="'.$label['nns_id'].$program_id.'" ParentCode="'.$vod_id.'" ElementCode="'.$label['nns_id'].$program_id.'" Action="REGIST">';
				$xml_str .= '</Mapping>';
			}
		}

		if($sp_id=='jllt'  || $sp_id=='nmgutl' || $sp_id=='xjcbc_dx_hw' || $sp_id=='xjcbc_dx_zte' || $sp_id=='xjdx_hw' || $sp_id=='cbczq_hw'){
			//绑定服务包
			$str_temp_vod = 'VOD';
			if($sp_id=='xjdx_hw' || $sp_id=='cbczq_hw')
			{
				$str_temp_vod='KKTV';
			}
			else
			{
				$temp_program_id = $program_id;
			}
			$xml_str .= '<Mapping ParentType="Package" ParentID="'.$str_temp_vod.'" ElementType="Series" ElementID="'.$temp_program_id.'" Action="REGIST" ParentCode="'.$str_temp_vod.'" ElementCode="'.$temp_program_id.'">';
			$xml_str .= '<Property Name="ValidStart">20140101000000</Property>';
			$xml_str .= '<Property Name="ValidEnd">20540101000000</Property>';
			$xml_str .= '</Mapping>';
		}

		$xml_str .= '</Mappings>';
		}
		
		
		$xml_str .= '</ADI>';

		//echo $xml_str;die;
		$guid = np_guid_rand();
		$time = date('YmdHis') . rand(0, 10000);
		$three_rand = rand(100, 999);
		$file_name = 'zgcms_'. $time .'_' . 'series' .'_'. $action . '_' . $three_rand. '.xml';

		//
		$c2_info = array(
		'nns_task_type'=>'Series',
		'nns_task_id'=> isset($vod_info['nns_task_id'])?$vod_info['nns_task_id']:null,
		'nns_task_name'=> isset($vod_info['nns_task_name'])?$vod_info['nns_task_name']:null,
		'nns_action'=> $action,
		'nns_url' => $file_name,
		'nns_content' => $xml_str,
		'nns_desc' => 'Series,'.$action,
		);

		return self::execute_c2($c2_info,$sp_id);
	}
	/**
	 * 点播内容/点播分集
	 * $vod_info array(
	 * 'nns_id'   影片id/分集id
	 * 'nns_vod_id' 分集属于影片id
	 * 'nns_category_id'  影片的栏目id
	 * 'nns_series_flag' 连续剧分集标识
	 * )
	 * 目前实现上，给对方的影片id都是我方的分集id，因为片源是和分集关联的；
	 * 所以在删除影片时，也是用分集id删除
	 */
	static public function do_vod($vod_info,$action,$sp_id){
		//$action = 'REGIST';
		include dirname(dirname(__FILE__)).'/'.$sp_id.'/define.php';
		$program_id = $vod_info['nns_id'];//vod nns_vod_id index nns_vod_index_id
		$vod_id = $program_id;
		$sp_config = sp_model::get_sp_config($sp_id);
		if(isset($sp_config['import_id_mode'])&&strlen($sp_config['import_id_mode'])>0&&(int)$sp_config['import_id_mode']>0){
			$video_info = video_model::get_vod_index_info($program_id);
			switch ($sp_config['import_id_mode']) {
				case '1':
					$vod_id = '001000'.$video_info['nns_integer_id'];
					$vod_id = str_pad($vod_id,32,"0");
					break;
				case '2':
					$vod_id = $video_info['nns_import_id'];
					break;
				case '3':
					$vod_id = CSP_ID . '0001' . $video_info['nns_integer_id'];
					$vod_id = str_pad($vod_id,32,"0");
					break;
				case '4':
					$arr_csp_id = explode("|", CSP_ID);
					$str_lenth = strlen($arr_csp_id[0])+strlen($arr_csp_id[1])+1;
					$lest_num = 32-$str_lenth;
					$vod_id = $arr_csp_id[0].'2'.str_pad($video_info['nns_integer_id'], $lest_num, "0", STR_PAD_LEFT).$arr_csp_id[1];
					break;
			}
		}
		$temp_program_id = $vod_id;
		$BizDomain = self::get_BizDomain($sp_id);
		$xml_str = '<?xml version="1.0" encoding="UTF-8"?><ADI xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" BizDomain="'.$BizDomain.'" Priority="1">';
		$xml_str .= '<Objects>';

		$xml_str .= '<Object ElementType="Program" ID="' .$vod_id. '" Action="' . $action . '" Code="' .$vod_id. '">';
		
		if(empty($vod_info['nns_task_name'])){
			$vod_info['nns_task_name'] = self::get_task_name($vod_info['nns_task_id']);
		}
		if(empty($vod_info['nns_name'])){
			$vod_info['nns_name'] = $vod_info['nns_task_name'];
		}

		//到中兴或者华为name为别名
		if ($sp_id == 'xjcbc_dx_hw' || $sp_id == 'xjcbc_dx_zte' || $sp_id == 'xjdx_hw' || $sp_id == 'xjdx_zte' || $sp_id=='cbczq_hw' || $sp_id=='cbczq_zte')
		{
		    $vod_info['nns_alias_name']  = strlen($vod_info['nns_alias_name']) <1 ? $vod_info['nns_name'] : $vod_info['nns_alias_name'];
			$xml_str .= '<Property Name="Name">'.htmlspecialchars($vod_info['nns_alias_name'],ENT_QUOTES).'</Property>';
		}
		else
		{
			$xml_str .= '<Property Name="Name">'.htmlspecialchars($vod_info['nns_name'],ENT_QUOTES).'</Property>';
		}

		$xml_str .= '<Property Name="OrderNumber"></Property>';//节目订购编号
		$xml_str .= '<Property Name="OriginalName">'.htmlspecialchars($vod_info['nns_alias_name'],ENT_QUOTES).'</Property>';//原名
		$xml_str .= '<Property Name="SortName"></Property>';//索引名称供界面排序
		$xml_str .= '<Property Name="SearchName">'.$vod_info['nns_pinyin'].'</Property>';//搜索名称供界面搜索
		$xml_str .= '<Property Name="Genre">Genre</Property>';//Program的默认类别（Genre）
		$xml_str .= '<Property Name="ActorDisplay">'.htmlspecialchars($vod_info['nns_actor'],ENT_QUOTES).'</Property>';//演员列表(只供显示)
		$xml_str .= '<Property Name="WriterDisplay">'.htmlspecialchars($vod_info['nns_director'],ENT_QUOTES).'</Property>';//作者列表(只供显示)
		$xml_str .= '<Property Name="OriginalCountry">'.htmlspecialchars($vod_info['nns_area'],ENT_QUOTES).'</Property>';//国家地区
		$xml_str .= '<Property Name="Language">'.htmlspecialchars($vod_info['nns_language'],ENT_QUOTES).'</Property>';//语言
		$show_time = null;
		if($vod_info['nns_index_show_time']=='0000-00-00 00:00:00' || empty($vod_info['nns_index_show_time'])){
			$show_time = $vod_info['nns_show_time'];//影片基本信息上的上映时间
		}else{
			$show_time = $vod_info['nns_index_show_time'];//分集的上映时间
		}
		
		$xml_str .= '<Property Name="ReleaseYear">' .  date('Y',strtotime($show_time)).'</Property>';//上映年份(YYYY)
		$xml_str .= '<Property Name="OrgAirDate">' . date('Ymd',strtotime($show_time)).'</Property>';//首播日期(YYYYMMDD)
		$xml_str .= '<Property Name="LicensingWindowStart">'. date('YmdHis').'</Property>';//有效开始时间(YYYYMMDDHH24MiSS)
		$xml_str .= '<Property Name="LicensingWindowEnd">'. date('YmdHis',time()+ 10*365*24*60*60).'</Property>';//有效结束时间(YYYYMMDDHH24MiSS)
		$xml_str .= '<Property Name="DisplayAsNew">0</Property>';//新到天数
		$xml_str .= '<Property Name="DisplayAsLastChance">300</Property>';//剩余天数
		$xml_str .= '<Property Name="Macrovision">0</Property>';//拷贝保护标志0:无拷贝保护	1:有拷贝保护
		//$xml_str .= '<Property Name="Description">'.htmlspecialchars($vod_info['nns_summary'],ENT_QUOTES).'</Property>';//节目描述
		if($sp_id =='xjcbc_dx_zte' || $sp_id =='xjdx_zte' || $sp_id=='cbczq_zte')
		{
		    $xml_str .= '<Property Name="Description">'.htmlspecialchars(mb_substr($vod_info['nns_summary'],0,256,'utf-8'),ENT_QUOTES).'</Property>';//描述信息
		}
		elseif ($sp_id=='cqyx')
		{
		    $xml_str .= '<Property Name="Description">'.htmlspecialchars(mb_substr($vod_info['nns_summary'],0,128,'utf-8'),ENT_QUOTES).'</Property>';//描述信息
		}
		else
		{
            $xml_str .= '<Property Name="Description">'.htmlspecialchars(mb_substr($vod_info['nns_summary'],0,128,'utf-8'),ENT_QUOTES).'</Property>';//描述信息
		}
		$xml_str .= '<Property Name="PriceTaxIn"></Property>';//列表定价
		$xml_str .= '<Property Name="Status">1</Property>';//状态标志 0:失效 1:生效
		$xml_str .= '<Property Name="SourceType">1</Property>';//1: VOD 5: Advertisement
		$xml_str .= '<Property Name="SeriesFlag">'.$vod_info['nns_series_flag'].'</Property>';//0: 普通VOD 1: 连续剧剧集
// 		if(empty($vod_info['nns_kind']))
// 		{
// 			$vod_info['nns_kind'] = $vod_info['nns_keyword'];
// 		}
// 		$xml_str .= '<Property Name="Type">'.htmlspecialchars($vod_info['nns_kind'],ENT_QUOTES).'</Property>';//节目内容类型 字符串，表示内容类型，例如：电影，连续剧，新闻，体育…
		
		if($sp_id =='xjcbc_dx_zte' || $sp_id =='xjdx_zte' || $sp_id=='cbczq_zte' )
		{
			$xml_str .= '<Property Name="Type">MV</Property>';//演职角色名称
		}
		else
		{
			if(empty($vod_info['nns_kind']))
			{
				$vod_info['nns_kind'] = $vod_info['nns_keyword'];
			}
			$xml_str .= '<Property Name="Type">'.htmlspecialchars($vod_info['nns_kind'],ENT_QUOTES).'</Property>';//节目内容类型,字符串，表示内容类型，例如：电影，连续剧，新闻，体育…
		}
		if ($sp_id=='cqyx')
		{
		    $xml_str .= '<Property Name="Keywords">'.htmlspecialchars(mb_substr($vod_info['nns_keyword'],0,32,'utf-8'),ENT_QUOTES).'</Property>';//关键字
		}
		else
		{
            $xml_str .= '<Property Name="Keywords">'.htmlspecialchars(mb_substr($vod_info['nns_keyword'],0,32,'utf-8'),ENT_QUOTES).'</Property>';//关键字
		}
// 		$xml_str .= '<Property Name="Keywords">'.htmlspecialchars($vod_info['nns_keyword'],ENT_QUOTES).'</Property>';//关键字 多个关键字之间使用分号分隔
		$xml_str .= '<Property Name="Tags">1</Property>';//关联标签 多个标签之间使用分号分隔
		$xml_str .= '<Property Name="Reserve1"></Property>';//保留字段
		$xml_str .= '<Property Name="Reserve2"></Property>';//保留字段
		$xml_str .= '<Property Name="Reserve3"></Property>';//保留字段
		$xml_str .= '<Property Name="Reserve4"></Property>';//保留字段
		$xml_str .= '<Property Name="Reserve5"></Property>';//保留字段
		if($sp_id!='hndx' && $sp_id!='hnlt_zx' && $sp_id!='hndx_hw' && $sp_id!='xjcbc_dx_hw' && $sp_id!='xjcbc_dx_zte' && $sp_id!='xjdx_hw' && $sp_id!='cbczq_hw' && $sp_id!='xjdx_zte' && $sp_id!='cbczq_zte')
		{
			$xml_str .= '<Property Name="StorageType">1</Property>';//存储分发策略要求
		
			$xml_str .= '<Property Name="RMediaCode"></Property>';//关联内容唯一标识 ,为了支持表示不同屏的同一个内容关系
		}
		
		$xml_str .= '</Object>';
		if($sp_id!='hndx' && $sp_id!='hnlt_zx' && $sp_id!='hndx_hw' && $sp_id!='xjcbc_dx_hw' && $sp_id!='xjcbc_dx_zte' && $sp_id!='xjdx_hw' && $sp_id!='cbczq_hw' && $sp_id!='xjdx_zte' && $sp_id!='cbczq_zte' && $sp_id!='cqyx' && $sp_id!='cqyx_hw' && $sp_id != 'hljdx')
			{
				//演员
			$db = nn_get_db(NL_DB_READ);
			//$db->open();
			$sql = "select l.* from nns_video_label l ,nns_video_label_bind_1006 b where l.nns_id=b.nns_label_id and b.nns_video_id='".$program_id."' ";
			$yy_result = nl_db_get_all($sql,$db);
			if(is_array($yy_result)){
				foreach($yy_result as $label){
					$cast_name = $label['nns_name'];
					$first_name = $label['nns_name'];
					if(strlen($label['nns_name']) > 64){
						$cast_name = i_substr($label['nns_name'],30);
					}
					if(strlen($label['nns_name']) > 32){
						$first_name = i_substr($label['nns_name'],30);
					}
					$xml_str .= '<Object ElementType="Cast" ID="' .$label['nns_id']. '" Action="REGIST" Code="' .$label['nns_id']. '">';
					$xml_str .= '<Property Name="Name">'.htmlspecialchars($cast_name,ENT_QUOTES).'</Property>';//
					$xml_str .= '<Property Name="FirstName">'.htmlspecialchars($first_name,ENT_QUOTES).'</Property>';//
					$xml_str .= '</Object>';

					//我方没有演员角色关系表，这里将角色的id设置为 演员标签id+节目id，角色名称设为演员名
					$xml_str .= '<Object ElementType="CastRoleMap" ID="' .$label['nns_id'].$program_id. '" Action="REGIST" Code="' .$label['nns_id'].$program_id. '">';
					$xml_str .= '<Property Name="CastRole">演员</Property>';//演职角色名称
					$xml_str .= '<Property Name="CastID">'.$label['nns_id'].'</Property>';//人物ID
					$xml_str .= '<Property Name="CastCode">'.$label['nns_id'].'</Property>';//人物Code
					$xml_str .= '</Object>';

				}
			}
			//导演
			$sql = "select l.* from nns_video_label l ,nns_video_label_bind_1005 b where l.nns_id=b.nns_label_id and b.nns_video_id='".$program_id."' ";
			$dy_result = nl_db_get_all($sql,$db);
			if(is_array($dy_result)){
				foreach($dy_result as $label){
					$cast_name = $label['nns_name'];
					$first_name = $label['nns_name'];
					if(strlen($label['nns_name']) > 64){
						$cast_name = i_substr($label['nns_name'],30);
					}
					if(strlen($label['nns_name']) > 32){
						$first_name = i_substr($label['nns_name'],30);
					}

					$xml_str .= '<Object ElementType="Cast" ID="' .$label['nns_id']. '" Action="REGIST" Code="' .$label['nns_id']. '">';
					$xml_str .= '<Property Name="Name">'.htmlspecialchars($cast_name,ENT_QUOTES).'</Property>';//
					$xml_str .= '<Property Name="FirstName">'.htmlspecialchars($first_name,ENT_QUOTES).'</Property>';//
					$xml_str .= '</Object>';

					//我方没有演员角色关系表，这里将角色的id设置为 演员标签id+节目id，角色名称设为演员名
					$xml_str .= '<Object ElementType="CastRoleMap" ID="' .$label['nns_id'].$program_id. '" Action="REGIST" Code="' .$label['nns_id'].$program_id. '">';
					$xml_str .= '<Property Name="CastRole">导演</Property>';//演职角色名称
					$xml_str .= '<Property Name="CastID">'.$label['nns_id'].'</Property>';//人物ID
					$xml_str .= '<Property Name="CastCode">'.$label['nns_id'].'</Property>';//人物Code
					$xml_str .= '</Object>';

				}
			}
			if( isset($vod_info['nns_series_flag']) && $vod_info['nns_series_flag']==1){
				//图片	
				/*if(!empty($vod_info['nns_image'])){
					$img_save_name = str_replace('.JPG','.jpg',$vod_info['nns_image']);
					$pic_url = self::get_image_url($img_save_name);
					$xml_str .= '<Object ElementType="Picture" ID="' .$program_id.'_index_image'. '" Action="' . $action . '" Code="' .$program_id.'_index_image'. '">';
					$xml_str .= '<Property Name="FileURL">'.$pic_url.'</Property>';//图片文件URL, 此路径格式支持ftp、http两种方式
					$xml_str .= '<Property Name="Description"></Property>';//描述			
					$xml_str .= '</Object>';
				}*/		
			}else{
				//图片
				if(!empty($vod_info['nns_image0'])){
					if($action=='REGIST'){
						$img_save_name = str_replace('.JPG','.jpg',$vod_info['nns_image0']);
						//$img_save_name = str_replace('.JPG','.jpg',$vod_info['nns_image0']);
						$file_img = dirname(dirname(dirname(__FILE__))).'/data/downimg/'.$img_save_name;
						if(file_exists($file_img)){
							$pic_url = self::get_image_url($img_save_name,$sp_id);
							$xml_str .= '<Object ElementType="Picture" ID="' .$program_id.'_image0'. '" Action="' . $action . '" Code="' .$program_id.'_image0'. '">';
							$xml_str .= '<Property Name="FileURL">'.$pic_url.'</Property>';//图片文件URL, 此路径格式支持ftp、http两种方式
							$xml_str .= '<Property Name="Description"></Property>';//描述			
							$xml_str .= '</Object>';
						}
					}
				}
				/*if(!empty($vod_info['nns_image2'])){
					$img_save_name = str_replace('.JPG','.jpg',$vod_info['nns_image2']);
					$pic_url = self::get_image_url($img_save_name,$sp_id);
					$xml_str .= '<Object ElementType="Picture" ID="' .$program_id.'_image2'. '" Action="' . $action . '" Code="' .$program_id.'_image2'. '">';
					$xml_str .= '<Property Name="FileURL">'.$pic_url.'</Property>';//图片文件URL, 此路径格式支持ftp、http两种方式
					$xml_str .= '<Property Name="Description"></Property>';//描述			
					$xml_str .= '</Object>';
				}*/
			}
		}

		$xml_str .= '</Objects>';
		//if($sp_id!='hndx'){
		$xml_str .= '<Mappings>';
	
	
		if($sp_id!='hndx' && $sp_id!='hnlt_zx' && $sp_id!='hndx_hw' && $sp_id!='xjcbc_dx_hw' && $sp_id!='xjcbc_dx_zte' && $sp_id!='xjdx_hw' && $sp_id!='cbczq_hw' && $sp_id!='xjdx_zte' && $sp_id!='cbczq_zte')
		{
			//演员
			if(is_array($yy_result)){
				foreach($yy_result as $label){
					$xml_str .= '<Mapping ParentType="Program" ParentID="'.$vod_id.'" ElementType="CastRoleMap" ElementID="'.$label['nns_id'].$program_id.'" ParentCode="'.$vod_id.'" ElementCode="'.$label['nns_id'].$program_id.'" Action="REGIST">';
					$xml_str .= '</Mapping>';
				}
			}
			//导演
			if(is_array($dy_result)){
				foreach($dy_result as $label){
					$xml_str .= '<Mapping ParentType="Program" ParentID="'.$vod_id.'" ElementType="CastRoleMap" ElementID="'.$label['nns_id'].$program_id.'" ParentCode="'.$vod_id.'" ElementCode="'.$label['nns_id'].$program_id.'" Action="REGIST">';
					$xml_str .= '</Mapping>';
				}
			}
		}
		//如果是连续剧分集，绑定到连续剧
		if( isset($vod_info['nns_series_flag']) && $vod_info['nns_series_flag']==1)
		{
			$video_id = $vod_info['nns_vod_id'];
			
			if(isset($sp_config['import_id_mode'])&&strlen($sp_config['import_id_mode'])>0&&(int)$sp_config['import_id_mode']>0){
				$video_info = video_model::get_vod_info($video_id);
				switch ($sp_config['import_id_mode']) {
					case '1':
					    if ($sp_id == 'hndx')
                        {
                            $video_id = '001000'.$video_info['nns_integer_id'];
                            $video_id = str_pad($video_id,32,"0");
                        }
                        else
                        {
                            $video_id = '000000'.$video_info['nns_integer_id'];
                            $video_id = str_pad($video_id,32,"0");
                        }
						break;
					case '2':
						$video_id = $video_info['nns_asset_import_id'];
						break;
					case '3':
						$video_id = CSP_ID . '0000' . $video_info['nns_integer_id'];
						$video_id = str_pad($video_id,32,"0");
						break;
					case '4':
						$arr_csp_id = explode("|", CSP_ID);
						$str_lenth = strlen($arr_csp_id[0])+strlen($arr_csp_id[1])+1;
						$lest_num = 32-$str_lenth;
						$video_id = $arr_csp_id[0].'1'.str_pad($video_info['nns_integer_id'], $lest_num, "0", STR_PAD_LEFT).$arr_csp_id[1];
						break;
				}
			}

			$sequence = $vod_info['nns_index']+1;
            if(isset($sp_config['cdn_index_sequence_max']) && !empty($sp_config['cdn_index_sequence_max']))
            {
                if ($sequence > $sp_config['cdn_index_sequence_max'])
                {
                        $sequence = $sp_config['cdn_index_sequence_max'];
                }
            }
            else
            {
                if ($sequence > 999)
                {
                    $sequence = 999;
                }
            }
			if($action=='REGIST'){
				$xml_str .= '<Mapping ParentType="Series" ParentID="'.$video_id.'" ElementType="Program" ElementID="'.$vod_id.'" ParentCode="'.$video_id.'" ElementCode="'.$vod_id.'" Action="REGIST">';
				$xml_str .= '<Property Name="Sequence">'.$sequence.'</Property>';//
				$xml_str .= '</Mapping>';
			}

			/*/图片
			if(!empty($vod_info['nns_image'])){
				$xml_str .= '<Mapping ParentType="Picture" ParentID="'.$program_id.'_index_image'.'" ElementType="Program" ElementID="'.$program_id.'" ParentCode="'.$program_id.'_index_image'.'" ElementCode="'.$program_id.'" Action="' . $action . '">';
				//Picture时：0: 缩略图 1: 海报 2: 剧照 3: 图标 4: 标题图 5: 广告图 6: 草图 7: 背景图 9: 频道图片
				//10: 频道黑白图片 11: 频道Logo 12: 频道名字图片99: 其他
				$xml_str .= '<Property Name="Type">1</Property>';
				$xml_str .= '<Property Name="Sequence">0</Property>';//
				$xml_str .= '</Mapping>';
			}*/
		}else{

			if($sp_id!='hndx' && $sp_id!='hnlt_zx' && $sp_id!='hndx_hw' && $sp_id!='xjcbc_dx_hw' && $sp_id!='xjcbc_dx_zte' && $sp_id!='xjdx_hw' && $sp_id!='cbczq_hw' && $sp_id!='xjdx_zte' && $sp_id!='cbczq_zte' && $sp_id!='cqyx' && $sp_id!='cqyx_hw' && $sp_id != 'hljdx')
			{
				//栏目
				if(!empty($vod_info['nns_category_id']))
				{
					if(is_array($vod_info['nns_category_id'])){
						foreach($vod_info['nns_category_id'] as $nns_category_id){
						$xml_str .= '<Mapping ParentType="Category" ParentID="'.$nns_category_id.'" ElementType="Program" ElementID="'.$program_id.'" ParentCode="'.$nns_category_id.'" ElementCode="'.$program_id.'" Action="REGIST">';
						$xml_str .= '</Mapping>';
						}
					}else if(is_string($vod_info['nns_category_id'])){
						$xml_str .= '<Mapping ParentType="Category" ParentID="'.$vod_info['nns_category_id'].'" ElementType="Program" ElementID="'.$program_id.'" ParentCode="'.$vod_info['nns_category_id'].'" ElementCode="'.$program_id.'" Action="REGIST">';
						$xml_str .= '</Mapping>'; 
					}
				}
				//图片
				if(!empty($vod_info['nns_image0']))
				{
					if($action=='REGIST'){
						$img_save_name = str_replace('.JPG','.jpg',$vod_info['nns_image0']);
						//$img_save_name = str_replace('.JPG','.jpg',$vod_info['nns_image0']);
						$file_img = dirname(dirname(dirname(__FILE__))).'/data/downimg/'.$img_save_name;
						if(file_exists($file_img)){
							$xml_str .= '<Mapping ParentType="Picture" ParentID="'.$program_id.'_image0'.'" ElementType="Program" ElementID="'.$program_id.'" ParentCode="'.$program_id.'_image0'.'" ElementCode="'.$program_id.'" Action="' . $action . '">';
							//Picture时：0: 缩略图 1: 海报 2: 剧照 3: 图标 4: 标题图 5: 广告图 6: 草图 7: 背景图 9: 频道图片
							//10: 频道黑白图片 11: 频道Logo 12: 频道名字图片99: 其他
							$xml_str .= '<Property Name="Type">1</Property>'; 			
							$xml_str .= '<Property Name="Sequence">0</Property>';//
							$xml_str .= '</Mapping>';
						}
					}
				}
			/*if(!empty($vod_info['nns_image2'])){
				$xml_str .= '<Mapping ParentType="Picture" ParentID="'.$program_id.'_image2'.'" ElementType="Program" ElementID="'.$program_id.'" ParentCode="'.$program_id.'_image2'.'" ElementCode="'.$program_id.'" Action="' . $action . '">';
				$xml_str .= '<Property Name="Type">1</Property>';
				$xml_str .= '<Property Name="Sequence">1</Property>';//
				$xml_str .= '</Mapping>';
			}*/

			//添加服务包绑定
			/*$xml_str .= '<Mapping ParentType="Package" ParentID="VOD" ElementType="Program" ElementID="'.$program_id.'" Action="REGIST" ParentCode="VOD" ElementCode="'.$program_id.'" >';
				$xml_str .= '<Property Name="ValidStart">20140101000000</Property>';
				$xml_str .= '<Property Name="ValidEnd">20540101000000</Property>';
			$xml_str .= '</Mapping>';*/
			}
		}

		if($sp_id=='jllt'  || $sp_id=='nmgutl' || $sp_id=='xjcbc_dx_hw' || $sp_id=='xjcbc_dx_zte'  || $sp_id=='xjdx_hw' || $sp_id=='cbczq_hw' || $sp_id=='cqyx' || $sp_id=='cqyx_hw')
		{
			$str_temp_vod = 'VOD';
			if($sp_id=='xjdx_hw' || $sp_id=='cbczq_hw')
			{
				$str_temp_vod='KKTV';
			}
			elseif($sp_id=='cqyx_hw')
			{
				$str_temp_vod = '100402';
			}
			elseif($sp_id=='cqyx')
			{
				$str_temp_vod = '100426';
			}
			else
			{
				$temp_program_id = $program_id;
			}
			$xml_str .= '<Mapping ParentType="Package" ParentID="'.$str_temp_vod.'" ElementType="Program" ElementID="'.$temp_program_id.'" Action="REGIST" ParentCode="'.$str_temp_vod.'" ElementCode="'.$temp_program_id.'" >';
			$xml_str .= '<Property Name="ValidStart">20140101000000</Property>';
			$xml_str .= '<Property Name="ValidEnd">20540101000000</Property>';
			$xml_str .= '</Mapping>';
		}

		$xml_str .= '</Mappings>';
		//}
		$xml_str .= '</ADI>';
		$guid = np_guid_rand();
		$time = date('YmdHis') . rand(0, 10000);
		$three_rand = rand(100, 999);
		$file_name = 'zgcms_'. $time .'_' . 'program' .'_'. $action . '_' . $three_rand. '.xml';
		//self::execute_c2($file_name, $xml_str);

		$c2_info = array(
		//'nns_id' => $c2_info['c2_id'],
		'nns_task_type'=>'Program',
		'nns_task_id'=> isset($vod_info['nns_task_id'])?$vod_info['nns_task_id']:null,
		'nns_task_name'=> isset($vod_info['nns_task_name'])?$vod_info['nns_task_name']:null,
		'nns_action'=> $action,
		'nns_url' => $file_name,
		'nns_content' => $xml_str,
		//'nns_result' => '['.$result['ret'].']'.$result['desc'],
		'nns_desc' => 'Program,'.$action,
		);

		return self::execute_c2($c2_info,$sp_id);
	}

	static public function get_image_url($img_path,$sp_id){
		include dirname(dirname(__FILE__)).'/'.$sp_id.'/define.php';
		if(defined('HW_DOANLOAD_IMG_METHOD') && HW_DOANLOAD_IMG_METHOD=='ftp'){
			$img_url = HW_DOANLOAD_IMG_FTP.$img_path;
		}else{
			$img_url = nl_image::epg_video_image_url($img_path);
		}
		return $img_url;
	}
	//修改点播
	static public function update_vod($vod_info,$sp_id){
		if(file_exists(dirname(dirname(__FILE__)).'/'.$sp_id.'/models/child_c2_task_model.php')){
			include_once dirname(dirname(__FILE__)).'/'.$sp_id.'/models/child_c2_task_model.php';
			if(method_exists('child_c2_task_model','update_vod')){
				$re = child_c2_task_model::update_vod($vod_info,$sp_id);
				return $re;
			}
		}

		$action = 'UPDATE';
		return self::do_vod($vod_info,$action,$sp_id);
	}
	//添加点播
	static public function add_vod($vod_info,$sp_id){
		//echo $sp_id;
		//echo dirname(dirname(__FILE__)).'/'.$sp_id.'/models/child_c2_task_model.php';
		if(file_exists(dirname(dirname(__FILE__)).'/'.$sp_id.'/models/child_c2_task_model.php')){
			include_once dirname(dirname(__FILE__)).'/'.$sp_id.'/models/child_c2_task_model.php';
			if(method_exists('child_c2_task_model','add_vod')){
				$re = child_c2_task_model::add_vod($vod_info,$sp_id);
				return $re;
			}
		}

		$action = 'REGIST';
		return self::do_vod($vod_info,$action,$sp_id);
	}
	/**
	 * params
	 */
	static public function delete_vod($params,$sp_id,$type=null){
		include_once dirname(dirname(__FILE__)).'/'.$sp_id.'/define.php';
		
		$sp_config = sp_model::get_sp_config($sp_id);
		if(isset($sp_config['c2_import_cdn_model']) && $sp_config['c2_import_cdn_model'] !=0 && strlen($type) >0)
		{
		    include_once dirname(__FILE__).'/child_models/c2_task_assign.class.php';
		    $obj_c2_task_assign = new c2_task_assign();
		    
		    $temp_func = ($type == 'video') ? "do_video" : "do_index";
		    $result_c2_task_assign = $obj_c2_task_assign->auto_load_task_model($sp_config['c2_import_cdn_model'], $temp_func,null,$sp_id,$sp_config,$params);
		    if($result_c2_task_assign['ret'] !=2)
		    {
		        return ($result_c2_task_assign['ret'] == 0) ? true : false;
		    }
		}
		
		
		if(file_exists(dirname(dirname(__FILE__)).'/'.$sp_id.'/models/child_c2_task_model.php')){
			include_once dirname(dirname(__FILE__)).'/'.$sp_id.'/models/child_c2_task_model.php';
			if(method_exists('child_c2_task_model','delete_vod')){
				$re = child_c2_task_model::delete_vod($params,$sp_id);
				return $re;
			}
		}
		
		$action = 'DELETE';
		$program_id = $params['nns_id'];
		
		$sp_config = sp_model::get_sp_config($sp_id);
		if(isset($sp_config['import_id_mode'])&&strlen($sp_config['import_id_mode'])>0&&(int)$sp_config['import_id_mode']>0){
			$video_info = video_model::get_vod_index_info($program_id);
			switch ($sp_config['import_id_mode']) {
				case '1':
					$program_id = '001000'.$video_info['nns_integer_id'];
					$program_id = str_pad($program_id,32,"0");
					break;
				case '2':
					$program_id = $video_info['nns_import_id'];
					break;
				case '3':
					$program_id = CSP_ID . '0001' . $video_info['nns_integer_id'];
					$program_id = str_pad($program_id,32,"0");
					break;
				case '4':
					$arr_csp_id = explode("|", CSP_ID);
					$str_lenth = strlen($arr_csp_id[0])+strlen($arr_csp_id[1])+1;
					$lest_num = 32-$str_lenth;
					$program_id = $arr_csp_id[0].'2'.str_pad($video_info['nns_integer_id'], $lest_num, "0", STR_PAD_LEFT).$arr_csp_id[1];
					break;
			}
			
		}
		
		$BizDomain = self::get_BizDomain($sp_id);
		$xml_str = '<?xml version="1.0" encoding="UTF-8"?><ADI xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" BizDomain="'.$BizDomain.'" Priority="1">';
		$xml_str .= '<Objects>';
		$xml_str .= '<Object ElementType="Program" ID="' .$program_id. '" Action="' . $action . '" Code="' .$program_id. '">';	
		$xml_str .= '</Object>';
		$xml_str .= '</Objects>';
		$xml_str .= '</ADI>';

		$time = date('YmdHis') . rand(0, 10000);
		$three_rand = rand(100, 999);
		$file_name = 'zgcms_'. $time .'_' . 'program' .'_'. $action . '_' . $three_rand. '.xml';

		$c2_info = array(
		'nns_task_type'=>'Program',
		'nns_task_id'=> isset($params['nns_task_id'])?$params['nns_task_id']:null,
		'nns_task_name'=> isset($params['nns_task_name'])?$params['nns_task_name']:null,
		'nns_action'=>	$action,
		'nns_url' => $file_name,
		'nns_content' => $xml_str,
		'nns_desc' => 'Program,'.$action,
		);
		return self::execute_c2($c2_info,$sp_id);
		
	}
	/**
	 * 此方法不建议使用
	 * $params array('nns_ids')
	 */
	static public function delete_vods($params){
		$action = 'DELETE';
		
		//$program_id = $params['nns_id'];
		//self::do_vod($vod_info,$action);
		
		$xml_str = '<?xml version="1.0" encoding="UTF-8"?><ADI xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" BizDomain="2" Priority="1">';
		$xml_str .= '<Objects>';	
		foreach($params['nns_ids'] as $id){
			$xml_str .= '<Object ElementType="Program" ID="' .$id. '" Action="' . $action . '" Code="' .$id. '">';	
			$xml_str .= '</Object>';			
		}

		$xml_str .= '</Objects>';
		$xml_str .= '</ADI>';

		$guid = np_guid_rand();
		$time = date('YmdHis') . rand(0, 10000);
		$three_rand = rand(100, 999);
		$file_name = 'zgcms_'. $time .'_' . 'program' .'_'. $action . '_' . $three_rand. '.xml';
			
		$c2_info = array(
		'nns_id' => $c2_info['c2_id'],
		'nns_task_type'=>'Program',
		'nns_task_id'=> isset($params['nns_task_id'])?$params['nns_task_id']:null,
		'nns_task_name'=> isset($params['nns_task_name'])?$params['nns_task_name']:null,
		'nns_action'=>	$action,
		'nns_url' => $file_name,
		'nns_content' => $xml_str,
		//'nns_result' =>  '['.$result['ret'].']'.$result['desc'],
		'nns_desc' => 'Program,'.$action,
		);		
		return self::execute_c2($c2_info);
		
	}
	
	/**
	 * 新版注入CDN主媒资
	 */
	static public function do_series_v2($video_info,$sp_id)
	{
	    include dirname(dirname(__FILE__)).'/'.$sp_id.'/define.php';
	    DEBUG && i_write_log_core('--注入主媒资--');
	    $sp_config = sp_model::get_sp_config($sp_id);
	    if(isset($sp_config['c2_import_cdn_model']) && $sp_config['c2_import_cdn_model'] !=0 )
	    {
	        include_once dirname(__FILE__).'/child_models/c2_task_assign.class.php';
	        $obj_c2_task_assign = new c2_task_assign();
	        $result_c2_task_assign = $obj_c2_task_assign->auto_load_task_model($sp_config['c2_import_cdn_model'], 'do_video',null,$sp_id,$sp_config,$video_info);
	        if($result_c2_task_assign['ret'] !=2)
	        {
	            return $result_c2_task_assign['ret'] == 0 ? true : false;
	        }
	    }
	    return 0;
	}
	
	/**
	 * 新版注入CDN主媒资
	 */
	static public function do_program($index_info,$sp_id)
	{
	    include dirname(dirname(__FILE__)).'/'.$sp_id.'/define.php';
	    DEBUG && i_write_log_core('--注入分集--');
	    $sp_config = sp_model::get_sp_config($sp_id);
	    if(isset($sp_config['c2_import_cdn_model']) && $sp_config['c2_import_cdn_model'] !=0 )
	    {
	        include_once dirname(__FILE__).'/child_models/c2_task_assign.class.php';
	        $obj_c2_task_assign = new c2_task_assign();
	        $result_c2_task_assign = $obj_c2_task_assign->auto_load_task_model($sp_config['c2_import_cdn_model'], 'do_index',null,$sp_id,$sp_config,$index_info);
	        if($result_c2_task_assign['ret'] !=2)
	        {
	            return $result_c2_task_assign['ret'] == 0 ? true : false;
	        }
	    }
	    return 0;
	}
	
	/**
	 * 注入片源（以分集为单位,切片完成后调用）
	 * $index_media array(
	 * 'nns_video_id'
	 * 'nns_video_index_id'
	 * 'nns_task_id'
	 * 'nns_new_dir'
	 * 'nns_media_ids'
	 * )
	 */
	static public function add_movies_by_vod_index($index_media,$sp_id)
	{
		include dirname(dirname(__FILE__)).'/'.$sp_id.'/define.php';
		DEBUG && i_write_log_core('--注入片源--');
		
		$sp_config = sp_model::get_sp_config($sp_id);
		if(isset($sp_config['c2_import_cdn_model']) && $sp_config['c2_import_cdn_model'] !=0 )
		{
			include_once dirname(__FILE__).'/child_models/c2_task_assign.class.php';
			$obj_c2_task_assign = new c2_task_assign();
			$result_c2_task_assign = $obj_c2_task_assign->auto_load_task_model($sp_config['c2_import_cdn_model'], 'do_media',null,$sp_id,$sp_config,$index_media);
			if($result_c2_task_assign['ret'] !=2)
			{
				return $result_c2_task_assign['ret'] == 0 ? true : false;
			}
		}
		//如果发现有特殊的xml生成在这里判断
		if(file_exists(dirname(dirname(__FILE__)).'/'.$sp_id.'/models/child_c2_task_model.php'))
		{
			include_once dirname(dirname(__FILE__)).'/'.$sp_id.'/models/child_c2_task_model.php';
			if(method_exists('child_c2_task_model','add_movies_by_vod_index'))
			{
				$re = child_c2_task_model::add_movies_by_vod_index($index_media,$sp_id);
				return $re;
			} 
			if(method_exists('child_c2_task_model','add_movie'))
			{
				$re = child_c2_task_model::add_movie($index_media,$sp_id);
				 
				return $re;
			}
			
			//return true;
		}
		//die;
		$db = nn_get_db(NL_DB_WRITE);
		//$sql = "select nns_name from nns_vod_index where nns_id='".$index_media['nns_video_index_id']."'";
		//$nns_task_name= nl_db_get_col($sql,$db);
		
		$sql = "select nns_pinyin from nns_vod where nns_id='".$index_media['nns_video_id']."'";
		$pinyin = nl_db_get_col($sql,$db);
		
		//
		$action = 'REGIST';
		

		
		$sql = "select * from nns_vod_media where nns_deleted != 1 and nns_vod_id='{$index_media['nns_video_id']}' and nns_vod_index_id='{$index_media['nns_video_index_id']}' and nns_id='{$index_media['nns_media_id']}' order by nns_kbps desc limit 1";
		
		$medias = nl_db_get_all($sql,$db);
		if(is_array($medias) && count($medias)>0){
			$BizDomain = self::get_BizDomain($sp_id);
			$xml_str = '<?xml version="1.0" encoding="UTF-8"?><ADI xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" BizDomain="'.$BizDomain.'" Priority="1">';
			
			
			
			$program_id = $index_media['nns_media_id'];
			if(isset($sp_config['import_id_mode'])&&strlen($sp_config['import_id_mode'])>0&&(int)$sp_config['import_id_mode']>0){
				$video_info = video_model::get_vod_media_info($index_media['nns_media_id']);
				switch ($sp_config['import_id_mode']) {
					case '1':
					    if ($sp_id == 'hndx')
                        {
                            $program_id = '001000'.$video_info['nns_integer_id'];
                            $program_id = str_pad($program_id,32,"0");
                        }
                        else
                        {
                            $program_id = '002000'.$video_info['nns_integer_id'];
                            $program_id = str_pad($program_id,32,"0");
                        }
						break;
					case '2':
						$program_id = $video_info['nns_import_id'];
						break;
					case '3':
						$program_id = CSP_ID . '0002' . $video_info['nns_integer_id'];
						$program_id = str_pad($program_id,32,"0");
						break;
					case '4':
						$arr_csp_id = explode("|", CSP_ID);
						$str_lenth = strlen($arr_csp_id[0])+strlen($arr_csp_id[1])+1;
						$lest_num = 32-$str_lenth;
						$program_id = $arr_csp_id[0].'3'.str_pad($video_info['nns_integer_id'], $lest_num, "0", STR_PAD_LEFT).$arr_csp_id[1];
						break;
				}
			}
			$xml_str .= '<Objects>';
			if($sp_id!='hndx' && $sp_id!='hnlt' && $sp_id!='hnlt_zx' && $sp_id!='hndx_hw' && $sp_id!='hljdx' && $sp_id!='xjcbc_dx_hw' && $sp_id!='xjcbc_dx_zte' && $sp_id!='xjdx_hw' && $sp_id!='cbczq_hw' && $sp_id!='xjdx_zte' && $sp_id!='cbczq_zte' && $sp_id!='cqyx' && $sp_id!='cqyx_hw' && $sp_id != 'hljdx' && $sp_id != 'hljdx_hw')
			{
			
				$xml_str .= '<Object ElementType="Movie" ID="' .$program_id. '" Action="DELETE" Code="' .$program_id. '">';	
				$xml_str .= '</Object>';
			}
			
			$media = array();
			$media_arr = array();
			
			$media_url = "";
			foreach($medias as $media_item)
			{
				$mode = strtolower($media_item['nns_mode']);
				if(($sp_id == 'hndx' || $sp_id == 'hnlt' || $sp_id == 'hnlt_zx' || $sp_id=='hndx_hw') && ($mode == '4k' || $mode == 'sd'))
				{
					$mode = 'hd';
					$media_item['nns_mode'] = 'hd';
				}
				$media_arr[$mode] = $media_item;
				
			}
			
			//print_r($media_arr);
			if(!empty($media_arr['hd'])){
				$media = $media_arr['hd'];
			}else if(!empty($media_arr['std'])){
				$media = $media_arr['std'];
			}else if(!empty($media_arr['low'])){
				$media = $media_arr['low'];
			}
			if(empty($media)) return false;
			
				$video_profile =1;
				$mode = strtolower($media['nns_mode']);
				switch($mode){
					case 'std':
					$video_profile = 1;
					break;
					case 'hd':
					$video_profile = 5;
					break;
					case 'low':
					$video_profile = 3;
					break;
				}
				if((int)$sp_config['disabled_clip'] !== 2 && (int)$sp_config['disabled_clip'] !== 3)
				{				
					//判断片源的URL	
					if(empty($index_media['nns_date'])){
						$index_media['nns_date'] = nl_db_get_col("select nns_date from nns_mgtvbk_clip_task where nns_id='{$index_media['nns_clip_task_id']}'", $db);
					}		
					$url = MOVIE_FTP.$index_media['nns_date'].'/'.$index_media['nns_clip_task_id'].'/'.$pinyin.'-'.$media['nns_vod_index'].'.m3u8';
					if(!empty($index_media['nns_file_path'])){
						$url = MOVIE_FTP.$index_media['nns_file_path'];
					}
					//$url = 'ftp://hndx_m3u8:hndx_m3u81234@113.247.251.156:21//20150122/54c0640824e8fd7c798b3dbd12e6ea7f/index.m3u8';


					$bool = self::check_ftp_file($url,$sp_config);
					//-->start 优化检查ftp文件的返回信息说明 <author:feijian.gao date:2017-1-19>
					switch($bool['ret'])
					{
						case 0: //文件存在，查询成功
							break;
						case 1: //ftp连接失败
							nl_execute_by_db("update nns_mgtvbk_c2_task set nns_status=10 where nns_id='{$index_media['nns_task_id']}'", $db);
							break;
						case 2: //文件不存在
							nl_execute_by_db("update nns_mgtvbk_c2_task set nns_status=11 where nns_id='{$index_media['nns_task_id']}'", $db);
							break;
						case 3: //获取文件列表失败
							nl_execute_by_db("update nns_mgtvbk_c2_task set nns_status=11 where nns_id='{$index_media['nns_task_id']}'", $db);
							break;
					}
					//获取切片后的片源文件失败，是否重新进行切片
					if($bool['ret'] != 0 && $sp_config['clip_file_repeat_enable'] != 0)
					{
						DEBUG && i_write_log_core('path_fail----'.$url,$sp_id.'/path_fail');
						include_once 'queue_task_model.php';
						$queue_task_model = new queue_task_model();
						$queue_task_model->q_re_clip($index_media['nns_task_id']);
						$queue_task_model=null;
						return false;
					}
					//--end

//					if($bool===false){
//						DEBUG && i_write_log_core('path_fail----'.$url,$sp_id.'/path_fail');
//						nl_execute_by_db("update nns_mgtvbk_c2_task set nns_status=-1 where nns_id='{$index_media['nns_task_id']}'", $db);
//						include_once 'queue_task_model.php';
//						$queue_task_model = new queue_task_model();
//
//						$queue_task_model->q_re_clip($index_media['nns_task_id']);
//						//$queue_task_model->q_add_task($index_media['nns_media_id'], 'media', 'add',$sp_id,null,true);
//						$queue_task_model=null;
//						return false;
//					}
				}
				else 
				{
					if(strpos($medias[0]['nns_url'],'http://') === false || strpos($medias[0]['nns_url'],'ftp://') === false)
					{
						$url = rtrim(MOVIE_FTP,'/') . '/'. ltrim($medias[0]['nns_url'],'/');
					}
					else
					{
						$url = $medias[0]['nns_url'];
					}
				}
				if($sp_id=='cqyx_hw')
				{
					$url = MOVIE_FTP.strrchr($medias[0]['nns_url'],'/');
				}
				$xml_str .= '<Object ElementType="Movie" ID="' .$program_id. '" Action="' . $action . '" Code="' .$program_id. '" >';
				$xml_str .= '<Property Name="Type">1</Property>';//媒体类型1:正片 2:预览片
				$xml_str .= '<Property Name="FileURL">' .$url. '</Property>';//媒体文件URL,ftp://username:password@ip:port/...  标准FTP协议
				$xml_str .= '<Property Name="SourceDRMType">1</Property>';//0: No DRM 1: BES DRM
				$xml_str .= '<Property Name="DestDRMType">1</Property>';//
				$xml_str .= '<Property Name="AudioType">1</Property>';//0: 其他 1: Monaural 单声道 2: Stereo 多声道 3: Two-nation monaural 双单声道 4: Two-nation stereo 双多声道  5: AC3(5:1 channel) AC3声道
				$xml_str .= '<Property Name="ClosedCaptioning">1</Property>';//0:无字幕 1:有字幕
				if($sp_id!='hndx' && $sp_id!='hnlt_zx' && $sp_id!='hljdx' && $sp_id!='hndx_hw' && $sp_id!='xjcbc_dx_hw' && $sp_id!='xjcbc_dx_zte' && $sp_id!='xjdx_hw' && $sp_id!='cbczq_hw' && $sp_id!='xjdx_zte' && $sp_id!='cbczq_zte')
				{
					$xml_str .= '<Property Name="OCSURL"></Property>';//在海量存储中的视频URL，类似Rtsp://ip:port/1/2/3.ts		
					$xml_str .= '<Property Name="Duration"></Property>';//播放时长HHMISSFF （时分秒帧）
					$xml_str .= '<Property Name="FileSize">1024</Property>';//文件大小，单位为Byte
					$xml_str .= '<Property Name="BitRateType">1</Property>';//码流;1:1.6Mbps 2:2.1Mbps 3:8Mbps 4:60kbps 5:150kbps 6:420kbps 7:750kbps
					$xml_str .= '<Property Name="VideoType">1</Property>';//编码格式： 1:H.264 2:MPEG4 3:AVS 4:MPEG2 5:MP3 6:WMV
					$xml_str .= '<Property Name="AudioFormat">1</Property>';//编码格式：1.	MP2 2.	AAC 3.	AMR
					$xml_str .= '<Property Name="Resolution">1</Property>';//分辨率类型：1:QCIF 2:QVGA 3:2/3 D1 4:3/4 D1 5:D1 6:720P 7:1080i 8:1080P
					$xml_str .= '<Property Name="VideoProfile">'.$video_profile.'</Property>';//1:Simple 2:Advanced Simple 3:Baseline 4:Main 5:High 6:JiZhun
					$xml_str .= '<Property Name="SystemLayer">1</Property>';//1:TS 2:3GP
					$xml_str .= '<Property Name="ServiceType">0x01</Property>';//服务类型:0x01：在线播放(默认) 0x10：支持下载 0X11:  在线播放+下载		
				}
				$xml_str .= '</Object>';
			   // break;
			//}
			$xml_str .= '</Objects>';
			
			//foreach($medias as $media){
				$nns_video_index_id = $index_media['nns_video_index_id'];		
				if(isset($sp_config['import_id_mode'])&&strlen($sp_config['import_id_mode'])>0&&(int)$sp_config['import_id_mode']>0){
					$video_info = video_model::get_vod_index_info($index_media['nns_video_index_id']);
					switch ($sp_config['import_id_mode']) {
						case '1':
							$nns_video_index_id = '001000'.$video_info['nns_integer_id'];
							$nns_video_index_id = str_pad($nns_video_index_id,32,"0");
							break;
						case '2':
							$nns_video_index_id = $video_info['nns_import_id'];
							break;
						case '3':
							$nns_video_index_id = CSP_ID . '0001' . $video_info['nns_integer_id'];
							$nns_video_index_id = str_pad($nns_video_index_id,32,"0");
							break;
						case '4':
							$arr_csp_id = explode("|", CSP_ID);
							$str_lenth = strlen($arr_csp_id[0])+strlen($arr_csp_id[1])+1;
							$lest_num = 32-$str_lenth;
							$nns_video_index_id = $arr_csp_id[0].'2'.str_pad($video_info['nns_integer_id'], $lest_num, "0", STR_PAD_LEFT).$arr_csp_id[1];
							break;
					}
					
				}	
			//if($sp_id!='hndx'){
				$xml_str .= '<Mappings>';
				$xml_str .= '<Mapping ParentType="Program" ParentID="'.$nns_video_index_id.'" ElementType="Movie" ElementID="'.$program_id.'" ParentCode="'.$nns_video_index_id.'" ElementCode="'.$program_id.'" Action="'.$action.'">';
				$xml_str .= '</Mapping>';
			//}
				$xml_str .= '</Mappings>';
			//}		
			$xml_str .= '</ADI>';
			
			//die($xml_str);
			$guid = np_guid_rand();
			$time = date('YmdHis') . rand(0, 10000);
			$three_rand = rand(100, 999);
			$file_name = 'zgcms_'. $time .'_' . 'vod_media' .'_'. $action . '_' . $three_rand. '.xml';


			$c2_info = array(
			//'nns_id' => $c2_info['c2_id'],
			'nns_task_type'=>'Movie',
			'nns_task_id'=> isset($index_media['nns_task_id'])?$index_media['nns_task_id']:null,
			'nns_task_name'=> isset($index_media['nns_task_name'])?$index_media['nns_task_name']:null,	
			'nns_action'=>	$action,
			'nns_url' => $file_name,
			'nns_content' => $xml_str,
			//'nns_result' =>  '['.$result['ret'].']'.$result['desc'],
			'nns_desc' => 'Movie,'.$action,
			);
			
			
			if((int)$sp_config['disabled_clip'] !== 2 && (int)$sp_config['disabled_clip'] !== 3)
			{
				//修改切片的状态
				
				$clip_task_id = $index_media['nns_clip_task_id'];
				
				
				
				//更改状态
				$dt = date('Y-m-d H:i:s');
				$set_state = array(
				'nns_state' => clip_task_model::TASK_C_STATE_C2_HANDLE,
				'nns_desc' => clip_task_model::$task_state_arr[clip_task_model::TASK_C_STATE_C2_HANDLE],
				'nns_modify_time'=>$dt,
				);
				clip_task_model::update_task($clip_task_id, $set_state);
						
						
				//任务日志	
				$task_log = array(
					'nns_task_id' => $clip_task_id,
					'nns_state'   => clip_task_model::TASK_C_STATE_C2_HANDLE,
					'nns_desc'	=> clip_task_model::$task_state_arr[clip_task_model::TASK_C_STATE_C2_HANDLE],
				);	
				clip_task_model::add_task_log($task_log);
			}
			
			
			return self::execute_c2($c2_info,$sp_id);

		}else{
			DEBUG && i_write_log_core('--没有片源--');
			nl_execute_by_db("update nns_mgtvbk_c2_task  set nns_status=1,nns_action='destroy',nns_epg_status=97 where nns_id='{$index_media['nns_task_id']}'", $db);
		}
		
	}
	static public function  add_movies_by_clip_task($task_id){
		
		$db = nn_get_db(NL_DB_READ);
		$task_info = clip_task_model::get_task_by_id($task_id);
		if(empty($task_info['nns_content'])){
			$task_info['nns_content'] = clip_task_model::_build_task_content($task_info);
		}
		
		$dom	= new DOMDocument('1.0', 'utf-8');
		$dom -> loadXML($task_info['nns_content']);		
		$xpath = new DOMXPath($dom);

		$nns_vod_id = $xpath->query('/task/video')->item(0)->getAttribute('id');
		$nns_vod_index_id = $xpath->query('/task/video/index_list/index')->item(0)->getAttribute('id');
		
		$nns_media_ids = array();
		$entries = $xpath->query('/task/video/index_list/index/media_list/media');
		foreach($entries as $item){
			$nns_media_ids[] = $item->getAttribute('id');
		}
		$media_info['nns_video_id'] = $nns_vod_id;
		$media_info['nns_video_index_id'] = $nns_vod_index_id;
		$media_info['nns_media_ids'] = $nns_media_ids;
		$media_info['nns_task_id'] = $task_id;
		$media_info['nns_new_dir'] = isset($task_info['nns_new_dir']) ? (empty($task_info['nns_new_dir']) ? false : true) : false;
		$media_info['nns_date'] = empty($task_info['nns_date'])?'':$task_info['nns_date'];
		
		$index_name = nl_db_get_col("select nns_name from nns_vod_index where nns_id='".$nns_vod_index_id."'",$db);
		//判断是否曾注入成功，是则先删除后重新注入
		$sql = "select * from nns_mgtvbk_clip_task_log where nns_video_index_id='".$nns_vod_index_id."' and nns_state='c2_ok' limit 1";
		$result = nl_query_by_db($sql,$db);
		if(!is_bool($result)){
			DEBUG && i_write_log_core('--注入片源前，先执行删除指令--');
			//先删除再重新注入
			$_params_del = array(
			'nns_ids'=>$nns_media_ids,
			'nns_task_id'=> $task_id,
			'nns_task_name'=> $index_name,
			);
			self::delete_movies($_params_del);
		}
		return self::add_movies_by_vod_index($media_info);
	}
	/**
	 *   该方法仅供测试用
	 */
	static public function test_add_movies_by_vod_index($index_media){
		DEBUG && i_write_log_core('--注入片源--');
		$action = 'REGIST';
		$db = nn_get_db(NL_DB_READ);
		//$db->open();
		//先注入vod及index;否则，注入的片源将没有绑定任何影片
		$sql = "select nns_id from nns_mgtvbk_c2_task " .
				"where nns_ref='".$index_media['nns_video_id']."'" .
						" and nns_action='".SP_ORG_ID."'" .
						" and nns_type='vod' and nns_status>0 limit 1";
		$result = nl_db_get_col($sql,$db);				
		if($result != false){
			DEBUG && i_write_log_core('--注入片源时，注入影片内容--');
			include_once dirname(__FILE__).'/content_task_model.php';
			content_task_model::vod($result);
		}		
		$sql = "select nns_pinyin from nns_vod where nns_id='".$index_media['nns_video_id']."'";
		$pinyin = nl_db_get_col($sql,$db);
				
		$sql = "select * from nns_vod_media where nns_deleted != 1 and ".nl_db_in($index_media['nns_media_ids'],'nns_id');
		$medias = nl_db_get_all($sql,$db);
		if($medias === false ) {
			DEBUG && i_write_log_core('--取片源出错--'."\n".var_export($medias,true)."\n".$sql);
			return false;
			}
		if(is_array($medias) && count($medias)>0){
			$xml_str = '<?xml version="1.0" encoding="UTF-8"?><ADI xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" BizDomain="2" Priority="1">';
			$xml_str .= '<Objects>';
			foreach($medias as $media){
				//$url = 'ftp://username:password@ip:port/'.$index_media['nns_vod_index_id'].'/'.$media['nns_id'].'.m3u8';
				$video_profile =1;
				$mode = strtolower($media['nns_mode']);
				switch($mode){
					case 'std':
					$video_profile = 1;
					break;
					case 'hd':
					$video_profile = 5;
					break;
					case 'low':
					$video_profile = 3;
					break;
				}
				//$kbps_index = clip_task_model::get_kbps_index($media['nns_mode']);
				if($pinyin){
					$url = MOVIE_FTP.$index_media['nns_date'].'/'.$media['nns_vod_index_id'].'/'.$pinyin.'-'.$media['nns_vod_index'].'.m3u8';
				}else{
					$url = MOVIE_FTP.$index_media['nns_date'].'/'.$media['nns_vod_index_id'].'/index.m3u8';
				}	
				$xml_str .= '<Object ElementType="Movie" ID="' .$media['nns_id']. '" Action="' . $action . '" Code="' .$media['nns_id']. '" >';			
				$xml_str .= '<Property Name="Type">1</Property>';//媒体类型1:正片 2:预览片
				$xml_str .= '<Property Name="FileURL">' .$url. '</Property>';//媒体文件URL,ftp://username:password@ip:port/...  标准FTP协议
				$xml_str .= '<Property Name="SourceDRMType">1</Property>';//0: No DRM 1: BES DRM
				$xml_str .= '<Property Name="DestDRMType">1</Property>';//
				$xml_str .= '<Property Name="AudioType">1</Property>';//0: 其他 1: Monaural 单声道 2: Stereo 多声道 3: Two-nation monaural 双单声道 4: Two-nation stereo 双多声道  5: AC3(5:1 channel) AC3声道
				$xml_str .= '<Property Name="ClosedCaptioning">1</Property>';//0:无字幕 1:有字幕
				$xml_str .= '<Property Name="OCSURL"></Property>';//在海量存储中的视频URL，类似Rtsp://ip:port/1/2/3.ts		
				$xml_str .= '<Property Name="Duration"></Property>';//播放时长HHMISSFF （时分秒帧）
				$xml_str .= '<Property Name="FileSize">1024</Property>';//文件大小，单位为Byte
				$xml_str .= '<Property Name="BitRateType">1</Property>';//码流;1:1.6Mbps 2:2.1Mbps 3:8Mbps 4:60kbps 5:150kbps 6:420kbps 7:750kbps
				$xml_str .= '<Property Name="VideoType">1</Property>';//编码格式： 1:H.264 2:MPEG4 3:AVS 4:MPEG2 5:MP3 6:WMV
				$xml_str .= '<Property Name="AudioFormat">1</Property>';//编码格式：1.	MP2 2.	AAC 3.	AMR
				$xml_str .= '<Property Name="Resolution">1</Property>';//分辨率类型：1:QCIF 2:QVGA 3:2/3 D1 4:3/4 D1 5:D1 6:720P 7:1080i 8:1080P
				$xml_str .= '<Property Name="VideoProfile">'.$video_profile.'</Property>';//1:Simple 2:Advanced Simple 3:Baseline 4:Main 5:High 6:JiZhun
				$xml_str .= '<Property Name="SystemLayer">1</Property>';//1:TS 2:3GP
				$xml_str .= '<Property Name="ServiceType">0x01</Property>';//服务类型:0x01：在线播放(默认) 0x10：支持下载 0X11:  在线播放+下载				
				$xml_str .= '</Object>';
				break;
			}
			$xml_str .= '</Objects>';	
			/*
			$xml_str .= '<Mappings>';
			foreach($medias as $media){
				//$xml_str .= '<Mapping ParentType="Program" ParentID="'.$index_media['nns_video_index_id'].'" ElementType="Movie" ElementID="'.$media['nns_id'].'" ParentCode="'.$index_media['nns_video_index_id'].'" ElementCode="'.$media['nns_id'].'" Action="'.$action.'">';
				$xml_str .= '<Mapping ParentType="Program" ParentID="123" ElementType="Movie" ElementID="'.$media['nns_id'].'" ParentCode="123" ElementCode="'.$media['nns_id'].'" Action="'.$action.'">';
				$xml_str .= '</Mapping>';
			}
			$xml_str .= '</Mappings>';
			*/	
			$xml_str .= '</ADI>';	

			$time = date('YmdHis') . rand(0, 10000);
			$three_rand = rand(100, 999);
			$file_name = 'zgcms_'. $time .'_' . 'vod_media' .'_'. $action . '_' . $three_rand. '.xml';

			//
			$c2_info = array(
			//'nns_id' => $c2_info['c2_id'],
			'nns_task_type'=>'Movie',
			'nns_task_id'=> isset($index_media['nns_task_id'])?$index_media['nns_task_id']:null,
			'nns_task_name'=> isset($index_media['nns_task_name'])?$index_media['nns_task_name']:null,		
			'nns_action'=>	$action,
			'nns_url' => $file_name,
			'nns_content' => $xml_str,
			'nns_result' =>  '['.$result['ret'].']'.$result['desc'],
			'nns_desc' => 'Movie,'.$action,
			);
			return self::execute_c2($c2_info);

		}else{
			DEBUG && i_write_log_core('--没有片源--');
		}
		
	}	
	/**
	 * 添加影片
	 */	
	static public function add_movie($media){
		$action = 'REGIST';
		return self::do_movie($media,$action);
	}
	
	
	
	/**
	 * 删除影片
	 * params array(
	 * nns_id,
	 * nns_task_id
	 * )
	 */
	static public function delete_movie($params,$sp_id)
	{
		include_once dirname(dirname(__FILE__)).'/'.$sp_id.'/define.php';
		$sp_config = sp_model::get_sp_config($sp_id);
		if(isset($sp_config['c2_import_cdn_model']) && $sp_config['c2_import_cdn_model'] !=0 )
		{
			include_once dirname(__FILE__).'/child_models/c2_task_assign.class.php';
			$obj_c2_task_assign = new c2_task_assign();
			$params['nns_media_id'] = $params['nns_id'];
			$result_c2_task_assign = $obj_c2_task_assign->auto_load_task_model($sp_config['c2_import_cdn_model'], 'do_media',null,$sp_id,$sp_config,$params);
			if($result_c2_task_assign['ret'] !=2)
			{
				return $result_c2_task_assign['ret'] == 0 ? true : false;
			}
		}
		if(file_exists(dirname(dirname(__FILE__)).'/'.$sp_id.'/models/child_c2_task_model.php'))
		{
			include_once dirname(dirname(__FILE__)).'/'.$sp_id.'/models/child_c2_task_model.php';
			if(method_exists('child_c2_task_model','delete_movie'))
			{
				$re = child_c2_task_model::delete_movie($params,$sp_id);
				return $re;
			}
			//return true;
		}
		$video_info = video_model::get_vod_media_info($params['nns_id']);
		
			if(isset($sp_config['import_id_mode'])&&strlen($sp_config['import_id_mode'])>0&&(int)$sp_config['import_id_mode']>0){
				
				switch ($sp_config['import_id_mode']) {
					case '1':
					    if ($sp_id == 'hndx')
                        {
                            $params['nns_id'] = '001000'.$video_info['nns_integer_id'];
                            $params['nns_id'] = str_pad($params['nns_id'],32,"0");
                        }
						else
                        {
                            $params['nns_id'] = '002000'.$video_info['nns_integer_id'];
                            $params['nns_id'] = str_pad($params['nns_id'],32,"0");
                        }
						break;
					case '2':
						$params['nns_id'] = $video_info['nns_import_id'];
						break;
					case '3':
						$params['nns_id'] = CSP_ID . '0002' . $video_info['nns_integer_id'];
						$params['nns_id'] = str_pad($params['nns_id'],32,"0");
						break;
					case '4':
						$arr_csp_id = explode("|", CSP_ID);
						$str_lenth = strlen($arr_csp_id[0])+strlen($arr_csp_id[1])+1;
						$lest_num = 32-$str_lenth;
						$params['nns_id'] = $arr_csp_id[0].'3'.str_pad($video_info['nns_integer_id'], $lest_num, "0", STR_PAD_LEFT).$arr_csp_id[1];
						break;
				}
				
			}
		
		$action = 'DELETE';
		$BizDomain = self::get_BizDomain($sp_id);
		//			
		//return self::do_movie($media,$action);
		$xml_str = '<?xml version="1.0" encoding="UTF-8"?><ADI xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" BizDomain="'.$BizDomain.'" Priority="1">';
		$xml_str .= '<Objects>';
		$xml_str .= '<Object ElementType="Movie" ID="' .$params['nns_id']. '" Action="' . $action . '" Code="' .$params['nns_id']. '">';	
		$xml_str .= '</Object>';
		$xml_str .= '</Objects>';
		
		
		
// 		if($sp_id == 'xjdx_zte')
// 		{
			
		
// 			$nns_video_index_id = $video_info['nns_vod_index_id'];
// 			if(isset($sp_config['import_id_mode'])&&strlen($sp_config['import_id_mode'])>0&&(int)$sp_config['import_id_mode']>0){
// 				$video_info = video_model::get_vod_index_info($video_info['nns_vod_index_id']);
// 				switch ($sp_config['import_id_mode']) {
// 					case '1':
// 						$nns_video_index_id = '001000'.$video_info['nns_integer_id'];
// 						$nns_video_index_id = str_pad($nns_video_index_id,32,"0");
// 						break;
// 					case '2':
// 						$nns_video_index_id = $video_info['nns_import_id'];
// 						break;
// 					case '3':
// 						$nns_video_index_id = CSP_ID . '0001' . $video_info['nns_integer_id'];
// 						$nns_video_index_id = str_pad($nns_video_index_id,32,"0");
// 						break;
// 					case '4':
// 						$arr_csp_id = explode("|", CSP_ID);
// 						$str_lenth = strlen($arr_csp_id[0])+strlen($arr_csp_id[1])+1;
// 						$lest_num = 32-$str_lenth;
// 						$nns_video_index_id = $arr_csp_id[0].'2'.str_pad($video_info['nns_integer_id'], $lest_num, "0", STR_PAD_LEFT).$arr_csp_id[1];
// 						break;
// 				}
					
// 			}
// 			$xml_str .= '<Mappings>';
// 			$xml_str .= '<Mapping ParentType="Program" ParentID="'.$nns_video_index_id.'" ElementType="Movie" ElementID="'.$params['nns_id'].'" ParentCode="'.$nns_video_index_id.'" ElementCode="'.$params['nns_id'].'" Action="'.$action.'">';
// 			$xml_str .= '</Mapping>';
// 			$xml_str .= '</Mappings>';
		
// 		}
		
		
		
		
		
		
		
		
		$xml_str .= '</ADI>';

		$time = date('YmdHis') . rand(0, 10000);
		$three_rand = rand(100, 999);
		$file_name = 'zgcms_'. $time .'_' . 'movie' .'_'. $action . '_' . $three_rand. '.xml';

				
		$c2_info = array(
		//'nns_id' => $c2_info['c2_id'],
		'nns_task_type'=>'Movie',
		'nns_task_id'=> isset($params['nns_task_id'])?$params['nns_task_id']:null,	
		'nns_task_name'=> isset($params['nns_task_name'])?$params['nns_task_name']:null,
		'nns_action'=>	$action,
		'nns_url' => $file_name,
		'nns_content' => $xml_str,
		//'nns_result' =>  '['.$result['ret'].']'.$result['desc'],
		'nns_desc' => 'Movie,'.$action,
		);
		
		
		//更改状态
		$dt = date('Y-m-d H:i:s');
		$set_state = array(
			'nns_state' => clip_task_model::TASK_C_STATE_C2_DELETE_HANDLE,
			'nns_desc' => clip_task_model::$task_state_arr[clip_task_model::TASK_C_STATE_C2_DELETE_HANDLE],
			'nns_modify_time'=>$dt,
		);
		clip_task_model::update_task($params['nns_clip_task_id'], $set_state);
				
					
		//任务日志	
		$task_log = array(
			'nns_task_id' => $params['nns_clip_task_id'],
			'nns_state'   => clip_task_model::TASK_C_STATE_C2_DELETE_HANDLE,
			'nns_desc'	=> clip_task_model::$task_state_arr[clip_task_model::TASK_C_STATE_C2_DELETE_HANDLE],
		);	
		clip_task_model::add_task_log($task_log);
		return self::execute_c2($c2_info,$sp_id);
		
	}
	/**
	 * 使用本方法时，请以分集为单位
	 * $params array(
	 * nns_ids
	 * )
	 */
	static public function delete_movies($params,$sp_id){
		$action = 'DELETE';
		
		$BizDomain = self::get_BizDomain($sp_id);
		//			
		//return self::do_movie($media,$action);
		$xml_str = '<?xml version="1.0" encoding="UTF-8"?><ADI xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" BizDomain="'.$BizDomain.'" Priority="1">';
		$xml_str .= '<Objects>';
		if(empty($params['nns_ids'] )) return ;
		foreach($params['nns_ids']  as $nns_id)	{
			$xml_str .= '<Object ElementType="Movie" ID="' .$nns_id. '" Action="' . $action . '" Code="' .$nns_id. '">';	
			$xml_str .= '</Object>';			
		}	

		$xml_str .= '</Objects>';
		$xml_str .= '</ADI>';
		
		$guid =  np_guid_rand();

		$time = date('YmdHis') . rand(0, 10000);
		$three_rand = rand(100, 999);
		$file_name = 'zgcms_'. $time .'_' . 'movie' .'_'. $action . '_' . $three_rand. '.xml';

		
		$c2_info = array(
		//'nns_id' => $c2_info['c2_id'],
		'nns_task_type'=>'Movie',
		'nns_task_id'=>  isset($params['nns_task_id'])?$params['nns_task_id']:null,
		'nns_task_name'=>  isset($params['nns_task_name'])?$params['nns_task_name']:null,		
		'nns_action'=>	$action,
		'nns_url' => $file_name,
		'nns_content' => $xml_str,
		//'nns_result' =>  '['.$result['ret'].']'.$result['desc'],
		'nns_desc' => 'Movie,'.$action,
		);		
		return self::execute_c2($c2_info,$sp_id);

	}

	//直播
	static public function add_live($live_info,$sp_id){

		if(file_exists(dirname(dirname(__FILE__)).'/'.$sp_id.'/models/child_c2_task_model.php')){
			include_once dirname(dirname(__FILE__)).'/'.$sp_id.'/models/child_c2_task_model.php';
			if(method_exists('child_c2_task_model','add_live')){
				$re = child_c2_task_model::add_live($live_info,$sp_id);
				return $re;
			}
		}
		
		
		$action = 'REGIST';
		//
		return self::do_live($live_info,$action,$sp_id);
	}
	static public function update_live($live_info,$sp_id){
		
		if(file_exists(dirname(dirname(__FILE__)).'/'.$sp_id.'/models/child_c2_task_model.php')){
			include_once dirname(dirname(__FILE__)).'/'.$sp_id.'/models/child_c2_task_model.php';
			if(method_exists('child_c2_task_model','update_live')){
				$re = child_c2_task_model::update_live($live_info,$sp_id);
				return $re;
			}
		}
		
		$action = 'UPDATE';
		//
		return self::do_live($live_info,$action,$sp_id);
	}
	/**
	 * params 
	 */
	static public function delete_live($params,$sp_id){
		
		
		if(file_exists(dirname(dirname(__FILE__)).'/'.$sp_id.'/models/child_c2_task_model.php')){
			include_once dirname(dirname(__FILE__)).'/'.$sp_id.'/models/child_c2_task_model.php';
			if(method_exists('child_c2_task_model','delete_live')){
				$re = child_c2_task_model::delete_live($live_info,$sp_id);
				return $re;
			}
		}
		
		$action = 'DELETE';
		$live_id = $params['nns_id'];
		//			
		//return self::do_movie($media,$action);
		$xml_str = '<?xml version="1.0" encoding="UTF-8"?><ADI xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" BizDomain="2" Priority="1">';
		$xml_str .= '<Objects>';
		$xml_str .= '<Object ElementType="Channel" ID="' .$live_id. '" Action="' . $action . '" Code="' .$live_id. '">';	
		$xml_str .= '</Object>';
		$xml_str .= '</Objects>';
		$xml_str .= '</ADI>';

		$time = date('YmdHis') . rand(0, 10000);
		$three_rand = rand(100, 999);
		$file_name = 'zgcms_'. $time .'_' . 'channel' .'_'. $action . '_' . $three_rand. '.xml';

		
		$c2_info = array(
		//'nns_id' => $c2_info['c2_id'],
		'nns_task_type'=>'Channel',
		'nns_task_id'=> isset($params['nns_task_id'])?$params['nns_task_id']:null,
		'nns_task_name'=> isset($params['nns_task_name'])?$params['nns_task_name']:null,		
		'nns_action'=>	$action,
		'nns_url' => $file_name,
		'nns_content' => $xml_str,
		//'nns_result' =>  '['.$result['ret'].']'.$result['desc'],
		'nns_desc' => 'Channel,'.$action,
		);		
		$db = nn_get_db(NL_DB_READ);
		$sql = "select * from nns_live_media where   nns_live_id='{$live_id}' and nns_deleted=0";
		$live_media = nl_db_get_all($sql, $db);
		foreach ($live_media as $key => $value) {
			$value['nns_task_name'] = $params['nns_task_name'];
			$value['nns_task_id'] = $params['nns_id'];
			self::delete_live_media($value,$action,$sp_id);
		}
		return self::execute_c2($c2_info,$sp_id);
	}

	/**
	 * 频道处理
	 * @param unknown $live_info
	 * @param unknown $action
	 * @param unknown $sp_id
	 */
	static public function do_channel($live_info,$action,$sp_id)
	{
	    if ($sp_id == 'hljdx' || $sp_id == 'hljdx_hw')
        {
            return self::do_channel_hljiptv_hw($live_info, $action, $sp_id);
        }
	    $sp_config = sp_model::get_sp_config($sp_id);
	    if(isset($sp_config['c2_import_cdn_model']) && $sp_config['c2_import_cdn_model'] !=0 )
	    {
	        include_once dirname(__FILE__).'/child_models/c2_task_assign.class.php';
	        $obj_c2_task_assign = new c2_task_assign();
	        $result_c2_task_assign = $obj_c2_task_assign->auto_load_task_model($sp_config['c2_import_cdn_model'], 'do_live',null,$sp_id,$sp_config,$live_info);
	        if($result_c2_task_assign['ret'] !=2)
	        {
	            return $result_c2_task_assign;
	        }
	    }
	    return true;
	}

    /**
     * 黑龙江华为模式直播频道注入，会将频道和频道片源组合成一个工单进行下发
     * @param array $item 注入指令信息数组
     * @param string $action 操作类型
     * @param string $sp_id SP ID
     * @return false 注入失败    true 注入成功
     * @author chunyang.shu
     * @date 2018-10-03
     */
    public static function do_channel_hljiptv_hw($item, $action, $sp_id)
    {
        // 创建DC对象
        $obj_dc = nl_get_dc(array (
            'db_policy'     => NL_DB_READ,
            'cache_policy'  => NP_KV_CACHE_TYPE_MEMCACHE
        ));

        // 获取直播频道详细信息
        include_once dirname(dirname(dirname(__FILE__))) . '/nn_logic/live/live.class.php';
        $arr_live_info = nl_live::query_by_id($obj_dc, $item['nns_channel_id']);
        if ($arr_live_info['ret'] != 0 || !isset($arr_live_info['data_info'])
            || !is_array($arr_live_info['data_info']) || empty($arr_live_info['data_info']))
        {
            return false;
        }
        $arr_live_info = $arr_live_info['data_info'];

        // 获取直播频道扩展信息
        include_once dirname(dirname(dirname(__FILE__))) . '/nn_logic/video/live_bo.class.php';
        $live_ex_list = nl_live_bo::get_live_ex_info($obj_dc, $item['nns_channel_id'], NL_DC_DB);
        if (false === $live_ex_list)
        {
            return false;
        }

        // 根据SP配置获取直播频道CDN注入ID
        $arr_live_import_info = public_model_exec::get_asset_id_by_sp_id($sp_id, 'live', $item['nns_channel_id'], $arr_live_info);
        if ($arr_live_import_info['ret'] != 0 || !isset($arr_live_import_info['data_info']) || strlen($arr_live_import_info['data_info']) == 0)
        {
            return false;
        }

        // 组装C2注入工单xml信息
        $str_channel_number = isset($live_ex_list['live_pindao_order']) ? $live_ex_list['live_pindao_order'] : '';
        $int_time_shift = 0;
        $int_time_shift_duration = 0;
        if (isset($live_ex_list['live_type']) && strlen($live_ex_list['live_type']) > 0)
        {
            $arr_live_type = explode(',', $live_ex_list['live_type']);
            if (in_array('TSTV', $arr_live_type))
            {
                $int_time_shift = 1;
                if (isset($live_ex_list['ts_default_pos']) && strlen($live_ex_list['ts_default_pos']) > 0)
                {
                    $int_time_shift_duration = ceil(intval($live_ex_list['ts_default_pos']) / 60);
                }
            }
        }
        $int_bizdomain = self::get_BizDomain($sp_id);
        $str_xml  = '<?xml version="1.0" encoding="UTF-8"?>';
        $str_xml .= '<ADI xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" BizDomain="' . $int_bizdomain . '" Priority="1">';
        $str_xml .= '<Objects>';

        // 组装频道信息
        $str_xml .= '<Object ElementType="Channel" ID="' . $arr_live_import_info['data_info'] . '" Action="' . $action
            . '" Code="' . $arr_live_import_info['data_info'] . '" >';
        $str_xml .= '<Property Name="ChannelNumber">' . $str_channel_number . '</Property>';
        $str_xml .= '<Property Name="Name">' . $arr_live_info['nns_name'] . '</Property>';
        $str_xml .= '<Property Name="CallSign"></Property>';
        $str_xml .= '<Property Name="TimeShift">' . $int_time_shift . '</Property>';
        $str_xml .= '<Property Name="StorageDuration"></Property>';
        $str_xml .= '<Property Name="TimeShiftDuration">' . $int_time_shift_duration . '</Property>';
        $str_xml .= '<Property Name="Description">' . $arr_live_info['nns_summary'] . '</Property>';
        $str_xml .= '<Property Name="Country"></Property>';
        $str_xml .= '<Property Name="State"></Property>';
        $str_xml .= '<Property Name="City"></Property>';
        $str_xml .= '<Property Name="ZipCode"></Property>';
        $str_xml .= '<Property Name="Type">1</Property>';
        $str_xml .= '<Property Name="SubType">1</Property>';
        $str_xml .= '<Property Name="Language"></Property>';
        $str_xml .= '<Property Name="Status">1</Property>';
        $str_xml .= '<Property Name="StartTime"></Property>';
        $str_xml .= '<Property Name="EndTime"></Property>';
        $str_xml .= '<Property Name="Macrovision"></Property>';
        $str_xml .= '<Property Name="Bilingual"></Property>';
        $str_xml .= '<Property Name="VSPCode"></Property>';
        $str_xml .= '</Object>';

        // 组装频道片源信息
        include_once dirname(dirname(dirname(__FILE__))) . '/nn_logic/live/live_media.class.php';
        $arr_params = array(
            'nns_live_id'   => $item['nns_channel_id'],
            'nns_deleted'   => 0
        );
        $arr_live_media_list = nl_live_media::query_by_condition($obj_dc, $arr_params);
        if ($arr_live_media_list['ret'] != 0)
        {
            return false;
        }
        $arr_live_media_info = is_array($arr_live_media_list['data_info'][0]) ? $arr_live_media_list['data_info'][0] : array();
        if (!empty($arr_live_media_info))
        {
            // 根据SP配置获取直播频道片源CDN注入ID
            $arr_media_import_info = public_model_exec::get_asset_id_by_sp_id($sp_id, 'live_media', $arr_live_media_info['nns_id'], $arr_live_media_info);
            if ($arr_media_import_info['ret'] != 0 || !isset($arr_media_import_info['data_info']) || strlen($arr_media_import_info['data_info']) == 0)
            {
                return false;
            }

            // 组装频道片源信息
            $str_multicast_ip = $str_multicast_port = '';
            if (strlen($arr_live_media_info['nns_url']) > 0)
            {
                $arr_url_info = parse_url($arr_live_media_info['nns_url']);
                $str_multicast_ip = strlen($arr_url_info['host']) > 0 ? $arr_url_info['host'] : '';
                $str_multicast_port = strlen($arr_url_info['port']) > 0 ? $arr_url_info['port'] : '';
            }
            $str_bit_rate_type = '';
            if (strlen($arr_live_media_info['nns_kbps']) > 0)
            {
                if ($arr_live_media_info['nns_kbps'] == 1024 * 8)
                {
                    $str_bit_rate_type = '6';
                }
                else
                {
                    $str_bit_rate_type = '5';
                }
            }
            $str_xml .= '<Object ElementType="PhysicalChannel" ID="' . $arr_media_import_info['data_info'] . '" Action="' . $action
                    . '" Code="' . $arr_media_import_info['data_info'] . '" >';
            $str_xml .= '<Property Name="ChannelCode">' . $arr_live_import_info['data_info'] . '</Property>';
            $str_xml .= '<Property Name="BitRateType">' . $str_bit_rate_type . '</Property>';
            $str_xml .= '<Property Name="MultiCastIP">' . $str_multicast_ip . '</Property>';
            $str_xml .= '<Property Name="MultiCastPort">' . $str_multicast_port . '</Property>';
            $str_xml .= '<Property Name="MediaSpec"></Property>';
            $str_xml .= '</Object>';
        }
        $str_xml .= '</Objects>';
        $str_xml .= '</ADI>';

        // 组装C2注入数据
        $str_file_name = $sp_id . '_cms_' . date('YmdHis') . '_' . rand(1000, 9999) . '_' . 'live' . '_' . $action . '_' .  rand(100, 999) . '.xml';
        $arr_c2_info = array(
            'nns_task_type' => 'Channel',
            'nns_task_id'   => $item['bk_c2_task_info']['nns_id'],
            'nns_task_name' => $item['bk_c2_task_info']['nns_name'],
            'nns_action'    => $action,
            'nns_url'       => $str_file_name,
            'nns_content'   => $str_xml,
            'nns_desc'      => 'Channel' . $action
        );

        // C2注入
        $result = self::execute_c2($arr_c2_info, $sp_id);
        $str_current_time = date('Y-m-d H:i:s');
        if (true === $result)
        {
            $str_sql = "update nns_mgtvbk_c2_task set nns_status=5,nns_modify_time='{$str_current_time}',nns_epg_status=97"
                . " where nns_id = '{$item['bk_c2_task_info']['nns_id']}'";
        }
        else
        {
            $str_sql = "update nns_mgtvbk_c2_task set nns_modify_time='{$str_current_time}',nns_epg_status=97"
                . ",nns_cdn_fail_time=nns_cdn_fail_time+1 where nns_id = '{$item['bk_c2_task_info']['nns_id']}'";
        }
        return nl_execute_by_db($str_sql, $obj_dc->db());
    }

	static public function do_live($live_info,$action,$sp_id)
    {
        if ($sp_id == 'hljdx' || $sp_id == 'hljdx_hw')
        {
            return self::do_physical_channel_v2($live_info, $action, $sp_id);
        }
		$sp_config = sp_model::get_sp_config($sp_id);
		if(isset($sp_config['c2_import_cdn_model']) && $sp_config['c2_import_cdn_model'] !=0 )
		{
			include_once dirname(__FILE__).'/child_models/c2_task_assign.class.php';
			$obj_c2_task_assign = new c2_task_assign();
			$result_c2_task_assign = $obj_c2_task_assign->auto_load_task_model($sp_config['c2_import_cdn_model'], 'do_live_media',null,$sp_id,$sp_config,$live_info);
			if($result_c2_task_assign['ret'] !=2)
			{
				return $result_c2_task_assign;
			}
		}
		$db = nn_get_db(NL_DB_READ);
		//查询直播ID
		$sql_str='select nns_value from nns_live_ex where nns_live_id="'.$live_info['nns_id'].'" and  nns_key="pid"';
		$live_info['nns_name_pid'] = nl_db_get_col($sql_str, $db);
		$xml_str = '<?xml version="1.0" encoding="UTF-8"?><ADI xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" BizDomain="2" Priority="1">';
		$xml_str .= '<Objects>';
		$xml_str .= '<Object ElementType="Channel" ID="' .$live_info['nns_id']. '" Action="' . $action . '" Code="' .$live_info['nns_id']. '">';	
		$xml_str .= '<Property Name="ChannelNumber"></Property>';//建议频道号,可以不填
		$xml_str .= '<Property Name="Name">'.$live_info['nns_name'].'</Property>';//频道名称
		$xml_str .= '<Property Name="CallSign">'.$live_info['nns_name_pid'].'</Property>';//台标名称
		$xml_str .= '<Property Name="TimeShift">1</Property>';//时移标志,0:不生效 1:生效
		$xml_str .= '<Property Name="StorageDuration">1</Property>';
		$xml_str .= '<Property Name="TimeShiftDuration">1</Property>';
		$xml_str .= '<Property Name="Description">1</Property>';//描述信息
		$xml_str .= '<Property Name="Country">1</Property>';
		$xml_str .= '<Property Name="State"></Property>';
		$xml_str .= '<Property Name="City"></Property>';
		$xml_str .= '<Property Name="ZipCode"></Property>';
		$xml_str .= '<Property Name="Type">1</Property>';//1:直播频道
		$xml_str .= '<Property Name="SubType"></Property>';
		$xml_str .= '<Property Name="Language"></Property>';
		$xml_str .= '<Property Name="Status">1</Property>';//状态标志,0:失效 1:生效
		$xml_str .= '<Property Name="StartTime">0001</Property>';
		$xml_str .= '<Property Name="EndTime">2359</Property>';
		$xml_str .= '<Property Name="Macrovision"></Property>';
		$xml_str .= '<Property Name="VideoType"></Property>';
		$xml_str .= '<Property Name="AudioType"></Property>';
		$xml_str .= '<Property Name="StreamType"></Property>';
		$xml_str .= '<Property Name="Bilingual"></Property>';
		$xml_str .= '<Property Name="URL"></Property>';//Web频道入口地址,当type=2时，这个属性必填					
		$xml_str .= '</Object>';
		$xml_str .= '</Objects>';
		if($sp_id=='jllt'){
		$live_info['nns_category_id'] = array(
			'30000008',
			'30000007'
		);
		}
		if(!empty($live_info['nns_category_id'])){
			$xml_str .= '<Mappings>';
		   	if(is_array($live_info['nns_category_id'])){
		   		foreach($live_info['nns_category_id'] as $nns_category_id){
					$xml_str .= '<Mapping ParentType="Category" ParentID="'.$nns_category_id.'" ElementType="Channel" ElementID="'.$live_info['nns_id'].'" ParentCode="'.$nns_category_id.'" ElementCode="'.$live_info['nns_id'].'" Action="REGIST">';
					$xml_str .= '</Mapping>';
		   		}
		   	}else if(is_string($live_info['nns_category_id'])){
				$xml_str .= '<Mapping ParentType="Category" ParentID="'.$live_info['nns_category_id'].'" ElementType="Channel" ElementID="'.$live_info['nns_id'].'" ParentCode="'.$live_info['nns_category_id'].'" ElementCode="'.$live_info['nns_id'].'" Action="REGIST">';
				$xml_str .= '</Mapping>';
		   	}
			if($sp_id=='jllt'  || $sp_id=='nmgutl' ){
			$xml_str .= '<Mapping ParentType="Package" ParentID="Channel" ElementType="Channel" ElementID="'.$live_info['nns_id'].'" Action="REGIST" ParentCode="Channel" ElementCode="'.$live_info['nns_id'].'" >';
			$xml_str .= '<Property Name="ValidStart">20140101000000</Property>';
			$xml_str .= '<Property Name="ValidEnd">20540101000000</Property>';
			$xml_str .= '</Mapping>';
			}

			$xml_str .= '</Mappings>';
		}
		$xml_str .= '</ADI>';

		$time = date('YmdHis') . rand(0, 10000);
		$three_rand = rand(100, 999);
		$file_name = 'zgcms_'. $time .'_' . 'live' .'_'. $action . '_' . $three_rand. '.xml';

		$c2_info = array(
		//'nns_id' => $c2_info['c2_id'],
		'nns_task_type'=>'Channel',
		'nns_task_id'=> isset($live_info['nns_task_id'])?$live_info['nns_task_id']:null,
		'nns_task_name'=> isset($live_info['nns_task_name'])?$live_info['nns_task_name']:null,	
		'nns_action'=>	$action,
		'nns_url' => $file_name,
		'nns_content' => $xml_str,
		//'nns_result' =>$result,
		'nns_desc' => 'Channel,'.$action,
		);

		/*
		 * @调用live_media//直接进华为命令
		 */
		self::execute_c2($c2_info,$sp_id);
		$sql = "select * from nns_live_media where   nns_live_id='{$live_info['nns_id']}' and nns_deleted=0";
		$live_media = nl_db_get_all($sql, $db);
		if(count($live_media)>0&&is_array($live_media)){
			self::add_live_media($live_media, $action,$live_info['nns_id'],$live_info['nns_name'],$sp_id);
		}
		return true;
	
	}
	
	
	static public function do_live_v2($live_info,$action,$sp_id){
		$db = nn_get_db(NL_DB_READ);
		//查询直播ID
		$sql_str='select nns_value from nns_live_ex where nns_live_id="'.$live_info['nns_id'].'" and  nns_key="pid"';
		$live_info['nns_name_pid'] = nl_db_get_col($sql_str, $db);
		$xml_str = '<?xml version="1.0" encoding="UTF-8"?><ADI xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" BizDomain="2" Priority="1">';
		$xml_str .= '<Objects>';
		$xml_str .= 	'<Object ElementType="Channel" ContentID="' .$live_info['nns_id']. '" Action="' . $action . '" Code="' .$live_info['nns_id']. '">';
		$xml_str .= 		'<Property Name="ChannelNumber">11111</Property>';//建议频道号,可以不填
		$xml_str .= 		'<Property Name="Name">'.$live_info['nns_name'].'</Property>';//频道名称
		$xml_str .= 		'<Property Name="CallSign">'.$live_info['nns_name_pid'].'</Property>';//台标名称
		$xml_str .= 		'<Property Name="TimeShift">1</Property>';//时移标志,0:不生效 1:生效
		$xml_str .= 		'<Property Name="Type">1</Property>';//1:直播频道
		$xml_str .= 		'<Property Name="Status">1</Property>';//状态标志,0:失效 1:生效
		$xml_str .= 		'<Property Name="StartTime">1000</Property>';
		$xml_str .= 		'<Property Name="EndTime">2359</Property>';
		$xml_str .= 		'<Property Name="CPContentID">2359</Property>';
		$xml_str .= 		'<Property Name="StorageDuration">1</Property>';
		$xml_str .= 		'<Property Name="TimeShiftDuration">20</Property>';
		$xml_str .= 		'<Property Name="Description">1</Property>';//描述信息
		$xml_str .= 		'<Property Name="Country">1</Property>';
		$xml_str .= 		'<Property Name="State"></Property>';
		$xml_str .= 		'<Property Name="City"></Property>';
		$xml_str .= 		'<Property Name="ZipCode"></Property>';
		$xml_str .= 		'<Property Name="SubType"></Property>';
		$xml_str .= 		'<Property Name="Language"></Property>';
		$xml_str .= 		'<Property Name="Macrovision"></Property>';
		$xml_str .= 		'<Property Name="VideoType"></Property>';
		$xml_str .= 		'<Property Name="AudioType"></Property>';
		$xml_str .= 		'<Property Name="StreamType"></Property>';
		$xml_str .= 		'<Property Name="Bilingual"></Property>';
		$xml_str .= 		'<Property Name="URL"></Property>';//Web频道入口地址,当type=2时，这个属性必填
		$xml_str .= 		'<Property Name="UniContentid">'.$live_info['nns_id'].'</Property>';
		$xml_str .= 	'</Object>';
		$xml_str .= '</Objects>';
		
		if(!empty($live_info['nns_category_id'])){
			$xml_str .= '<Mappings>';
			if(is_array($live_info['nns_category_id'])){
				foreach($live_info['nns_category_id'] as $nns_category_id){
					$xml_str .= '<Mapping ParentType="Category" ParentID="'.$nns_category_id.'" ElementType="Channel" ElementID="'.$live_info['nns_id'].'" ParentCode="'.$nns_category_id.'" ElementCode="'.$live_info['nns_id'].'" Action="REGIST">';
					$xml_str .= '</Mapping>';
				}
			}else if(is_string($live_info['nns_category_id'])){
				$xml_str .= '<Mapping ParentType="Category" ParentID="'.$live_info['nns_category_id'].'" ElementType="Channel" ElementID="'.$live_info['nns_id'].'" ParentCode="'.$live_info['nns_category_id'].'" ElementCode="'.$live_info['nns_id'].'" Action="REGIST">';
				$xml_str .= '</Mapping>';
			}
			if($sp_id=='jllt'  || $sp_id=='nmgutl' ){
				$xml_str .= '<Mapping ParentType="Package" ParentID="Channel" ElementType="Channel" ElementID="'.$live_info['nns_id'].'" Action="REGIST" ParentCode="Channel" ElementCode="'.$live_info['nns_id'].'" >';
				$xml_str .= '<Property Name="ValidStart">20140101000000</Property>';
				$xml_str .= '<Property Name="ValidEnd">20540101000000</Property>';
				$xml_str .= '</Mapping>';
			}
	
			$xml_str .= '</Mappings>';
		}
		$xml_str .= '</ADI>';
	
		$time = date('YmdHis') . rand(0, 10000);
		$three_rand = rand(100, 999);
		$file_name = 'zgcms_'. $time .'_' . 'live' .'_'. $action . '_' . $three_rand. '.xml';
	
		$c2_info = array(
				//'nns_id' => $c2_info['c2_id'],
				'nns_task_type'=>'Channel',
				'nns_task_id'=> isset($live_info['nns_task_id'])?$live_info['nns_task_id']:null,
				'nns_task_name'=> isset($live_info['nns_task_name'])?$live_info['nns_task_name']:null,
				'nns_action'=>	$action,
				'nns_url' => $file_name,
				'nns_content' => $xml_str,
				//'nns_result' =>$result,
				'nns_desc' => 'Channel,'.$action,
		);
		/*
		 * @调用live_media//直接进华为命令
		*/
// 		self::execute_c2($c2_info,$sp_id);
		$sql = "select * from nns_live_media where   nns_live_id='{$live_info['nns_id']}' and nns_deleted=0";
		$live_media = nl_db_get_all($sql, $db);
		if(count($live_media)>0&&is_array($live_media)){
			self::add_live_media_v2($live_media, $action,$live_info['nns_id'],$live_info['nns_name'],$sp_id);
		}
		return true;
	
	}

	/*
	 * 节目单
	 * @params array(
	 * 'nns_live_id',
	 * 'nns_task_id'
	 * )
	 */
	static public function add_playbill($item,$action=null,$sp_id=null){
		$sp_config = sp_model::get_sp_config($sp_id);
		if(isset($sp_config['c2_import_cdn_model']) && $sp_config['c2_import_cdn_model'] !=0 )
		{
			include_once dirname(__FILE__).'/child_models/c2_task_assign.class.php';
			$obj_c2_task_assign = new c2_task_assign();
			$result_c2_task_assign = $obj_c2_task_assign->auto_load_task_model($sp_config['c2_import_cdn_model'], 'do_playbill',null,$sp_id,$sp_config,$item);
			if($result_c2_task_assign['ret'] !=2)
			{
				return $result_c2_task_assign;
			}
		}
		$action = 'REGIST';
		
		$live_id = $item['nns_live_id'];
		$item['nns_task_name'] = $item['nns_name'];
		//$db = nn_get_db(NL_DB_WRITE);
		//$db->open();
		//$sql = "select * from nns_live_playbill_item where nns_live_id='$live_id'";		
		//$result = nl_db_get_all($sql,$db);
		//if(is_array($result) && count($result)>0){
			$xml_str = '<?xml version="1.0" encoding="UTF-8"?><ADI xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" BizDomain="2" Priority="1">';
			$xml_str .= '<Objects>';			
			//foreach($result as $item){
				$xml_str .= '<Object ElementType="Schedule" ID="' .$item['nns_id']. '" Action="' . $action . '" Code="' .$item['nns_id']. '">';	
				$xml_str .= '<Property Name="ChannelID">'.$item['nns_live_id'].'</Property>';
				$xml_str .= '<Property Name="ChannelCode">'.$item['nns_live_id'].'</Property>';
				$xml_str .= '<Property Name="ProgramName">'.$item['nns_name'].'</Property>';
				
				$xml_str .= '<Property Name="SearchName">'.$item['nns_name'].'</Property>';
				$xml_str .= '<Property Name="Genre">Genre</Property>';
				$xml_str .= '<Property Name="SourceType"></Property>';	
				$xml_str .= '<Property Name="StartDate">'.date('Ymd',strtotime($item['nns_begin_time'])).'</Property>';
				$xml_str .= '<Property Name="StartTime">'.date('His',$item['nns_begin_time']).'</Property>';
				$xml_str .= '<Property Name="Duration">'.date('His',$item['nns_time_len']).'</Property>';
				$xml_str .= '<Property Name="Status">1</Property>';
				$xml_str .= '<Property Name="Description">'.$item['nns_summary'].'</Property>';		
				
				$xml_str .= '<Property Name="ObjectType"></Property>';
				$xml_str .= '<Property Name="ObjectCode"></Property>';
		
				$xml_str .= '</Object>';
			//}
			$xml_str .= '</Objects>';
			$xml_str .= '</ADI>';

			$time = date('YmdHis') . rand(0, 10000);
			$three_rand = rand(100, 999);
			$file_name = 'zgcms_'. $time .'_' . 'schedule' .'_'. $action . '_' . $three_rand. '.xml';

			$c2_info = array();
			$c2_info['c2_id'] = np_guid_rand();
			$c2_info['file_name'] = $file_name;
			$c2_info['xml_content'] = $xml_str;

			$c2_info = array(
			//'nns_id' => $c2_info['c2_id'],
			'nns_task_type'=>'Schedule',
			'nns_task_id'=> isset($live_info['nns_task_id'])?$live_info['nns_task_id']:null,
			'nns_task_name'=> isset($live_info['nns_task_name'])?$live_info['nns_task_name']:null,
			'nns_action'=>	$action,
			'nns_url' => $file_name,
			'nns_content' => $xml_str,
			//'nns_result' =>$result,
			'nns_desc' => 'Schedule,'.$action,
			);			
			return self::execute_c2($c2_info);
		//}else{
		//	DEBUG && i_write_log_core('直播(id:'.$live_id.')没有节目单');
		//}
		//return false;
	}
	
	
	/**
	 * 文件包CDN执行
	 * @param unknown $item
	 * @param string $action
	 * @param string $sp_id
	 */
	static public function do_file($item,$action=null,$sp_id=null)
	{
	    $sp_config = sp_model::get_sp_config($sp_id);
	    if(isset($sp_config['c2_import_cdn_model']) && $sp_config['c2_import_cdn_model'] !=0 )
	    {
	        include_once dirname(__FILE__).'/child_models/c2_task_assign.class.php';
	        $obj_c2_task_assign = new c2_task_assign();
	        $result_c2_task_assign = $obj_c2_task_assign->auto_load_task_model($sp_config['c2_import_cdn_model'], 'do_file',null,$sp_id,$sp_config,$item);
	        if($result_c2_task_assign['ret'] !=2)
	        {
	            return $result_c2_task_assign;
	        }
	    }
	    return array(
	        'ret'=>0,
	        'reason'=>'ok no task'
	    );
	}
	/*
	 * 节目单
	* @params array(
		 * 'nns_live_id',
		 * 'nns_task_id'
		 * )
	*/
	static public function add_playbill_v2($item,$action,$sp_id){
	
		$live_id = $item['nns_live_id'];
		$item['nns_task_name'] = $item['nns_name'];
		//$db = nn_get_db(NL_DB_WRITE);
		//$db->open();
		//$sql = "select * from nns_live_playbill_item where nns_live_id='$live_id'";
		//$result = nl_db_get_all($sql,$db);
		//if(is_array($result) && count($result)>0){
		$xml_str = '<?xml version="1.0" encoding="UTF-8"?><ADI xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" BizDomain="2" Priority="1">';
		$xml_str .= '<Objects>';
		//foreach($result as $item){
		$xml_str .= '<Object ElementType="ScheduleRecord" PhysicalContentID="' .$item['nns_playbill_id']. '" ScheduleId="'.$item['nns_playbill_id'].'" PhysicalChannelID="'.$item['nns_live_media_id'].'" Action="' . $action . '" >';
		
		
// 		$xml_str .= '<Property Name="ScheduleId">'.$item['nns_playbill_id'].'</Property>';
// 		$xml_str .= '<Property Name="PhysicalChannelID">'.$item['nns_live_media_id'].'</Property>';
	
		$xml_str .= '<Property Name="StartDate">'.date('Ymd',strtotime($item['nns_begin_time'])).'</Property>';
		$xml_str .= '<Property Name="StartTime">'.date('His',strtotime($item['nns_begin_time'])).'</Property>';
		$xml_str .= '<Property Name="Duration">'.$item['nns_time_len'].'</Property>';
		$xml_str .= '<Property Name="CPContentID">1</Property>';
		$xml_str .= '<Property Name="UniContentId">'.$item['nns_id'].'</Property>';
		$xml_str .= '<Property Name="Description">'.$item['nns_summary'].'</Property>';
		$xml_str .= '<Property Name="Domain">257</Property>';
		$xml_str .= '<Property Name="HotDgree"></Property>';
	
		$xml_str .= '</Object>';
		//}
		$xml_str .= '</Objects>';
		$xml_str .= '</ADI>';
	
		$time = date('YmdHis') . rand(0, 10000);
		$three_rand = rand(100, 999);
		$file_name = 'zgcms_'. $time .'_' . 'schedule' .'_'. $action . '_' . $three_rand. '.xml';
	
		$c2_info = array();
		$c2_info['c2_id'] = np_guid_rand();
		$c2_info['file_name'] = $file_name;
		$c2_info['xml_content'] = $xml_str;
	
		$c2_info = array(
				//'nns_id' => $c2_info['c2_id'],
				'nns_task_type'=>'Schedule',
				'nns_task_id'=> isset($item['nns_playbill_id'])?$item['nns_playbill_id']:null,
				'nns_task_name'=> isset($item['nns_name'])?$item['nns_name']:null,
				'nns_action'=>	$action,
				'nns_url' => $file_name,
				'nns_content' => $xml_str,
				//'nns_result' =>$result,
				'nns_desc' => 'Schedule,'.$action,
		);
		return self::execute_c2($c2_info,$sp_id);
		//}else{
		//	DEBUG && i_write_log_core('直播(id:'.$live_id.')没有节目单');
		//}
		//return false;
	}

    /**
     * 节目单注入
     * @param array $item 注入指令信息数组
     * @param string $action 操作类型
     * @param string $sp_id SP ID
     * @return false 注入失败    true 注入成功
     * @author chunyang.shu
     * @date 2017-10-10
     */
    public static function do_playbill_v2($item, $action = '', $sp_id = '')
    {
        // 获取SP配置信息，如果SP的CDN注入模式不是老逻辑模式，自动加载其他模式的文件
        $arr_sp_config = sp_model::get_sp_config($sp_id);
        if (isset($arr_sp_config['c2_import_cdn_model']) && $arr_sp_config['c2_import_cdn_model'] != 0)
        {
            include_once dirname(__FILE__) . '/child_models/c2_task_assign.class.php';
            $obj_c2_task_assign = new c2_task_assign();
            $arr_result = $obj_c2_task_assign->auto_load_task_model(
                $arr_sp_config['c2_import_cdn_model'],
                'do_playbill',
                null,
                $sp_id,
                $arr_sp_config,
                $item
            );
            if($arr_result['ret'] != 2)
            {
                return $arr_result;
            }
        }

        // 创建DC对象
        $obj_dc = nl_get_dc(array (
            'db_policy'     => NL_DB_WRITE|NL_DB_READ,
            'cache_policy'  => NP_KV_CACHE_TYPE_MEMCACHE
        ));

        // 获取节目单详细信息
        include_once dirname(dirname(dirname(__FILE__))) . '/nn_logic/live/live.class.php';
        include_once dirname(dirname(dirname(__FILE__))) . '/nn_logic/live/playbill.class.php';
        
        
        $arr_playbill_info = nl_playbill::query_by_id($obj_dc, $item['nns_playbill_id']);
        if ($arr_playbill_info['ret'] != 0 || !isset($arr_playbill_info['data_info'])
            || !is_array($arr_playbill_info['data_info']) || empty($arr_playbill_info['data_info']))
        {
            return false;
        }
        $arr_playbill_info = $arr_playbill_info['data_info'];
        
        // 获取节目单所属频道详细信息
        $arr_live_info = nl_live::query_by_id($obj_dc, $arr_playbill_info['nns_live_id']);
        if ($arr_live_info['ret'] != 0 || !isset($arr_live_info['data_info'])
            || !is_array($arr_live_info['data_info']) || empty($arr_live_info['data_info']))
        {
            return false;
        }
        $arr_live_info = $arr_live_info['data_info'];
        
        // 根据SP配置获取节目单CDN注入ID
        $arr_playbill_import_info = public_model_exec::get_asset_id_by_sp_id($sp_id, 'playbill', $item['nns_playbill_id'], $arr_playbill_info);
        if ($arr_playbill_import_info['ret'] != 0 || !isset($arr_playbill_import_info['data_info']) || strlen($arr_playbill_import_info['data_info']) == 0)
        {
            return false;
        }
        // 根据SP配置获取频道CDN注入ID
        $arr_live_import_info = public_model_exec::get_asset_id_by_sp_id($sp_id, 'live', $arr_live_info['nns_id'], $arr_live_info);
        if ($arr_live_import_info['ret'] != 0 || !isset($arr_live_import_info['data_info']) || strlen($arr_live_import_info['data_info']) == 0)
        {
            return false;
        }
        $arr_temp_task= null;
        $int_bizdomain = self::get_BizDomain($sp_id);
        if(isset($arr_sp_config['playbill']['enabled']) && $arr_sp_config['playbill']['enabled'] == '1')
		{
		    $group_num = isset($arr_sp_config['playbill']['group_num']) ? (int)$arr_sp_config['playbill']['group_num'] : 100;
		    $group_num = $group_num >0 ? $group_num : 100;
		    $retry_time_add = isset($arr_sp_config['playbill_add']['retry_time']) ? (int)$arr_sp_config['playbill_add']['retry_time'] : 0;
		    $retry_time_add = $retry_time_add >=0 ? $retry_time_add : 0;
		    $retry_time_modify = isset($arr_sp_config['playbill_modify']['retry_time']) ? (int)$arr_sp_config['playbill_modify']['retry_time'] : 0;
		    $retry_time_modify = $retry_time_modify >=0 ? $retry_time_modify : 0;
		    $retry_time_destroy = isset($arr_sp_config['playbill_destroy']['retry_time']) ? (int)$arr_sp_config['playbill_destroy']['retry_time'] : 0;
		    $retry_time_destroy = $retry_time_destroy >=0 ? $retry_time_destroy : 0;
		    $bk_c2_task_info = $item['bk_c2_task_info'];

		    for($i=0;$i<2;$i++)
		    {
		        if($i==0)
		        {
		            $sql_query_temp = "(nns_action='destroy' and nns_cdn_fail_time<={$retry_time_destroy})";
		        }
		        else
		        {
		            $sql_query_temp = "((nns_action='add' and nns_cdn_fail_time<={$retry_time_add}) or (nns_action='modify' and nns_cdn_fail_time<={$retry_time_modify}))";
		        }
		        $sql_group="select * from nns_mgtvbk_c2_task where nns_status='1' and nns_type='playbill' and nns_src_id='{$bk_c2_task_info['nns_src_id']}' and nns_org_id='{$sp_id}' ".
		            " and {$sql_query_temp} order by nns_create_time asc limit {$group_num} ";
		        $result_group = nl_query_by_db($sql_group, $obj_dc->db());
		        if(!is_array($result_group) || empty($result_group))
		        {
		            continue;
		        }
		        foreach ($result_group as $val)
		        {
		            $arr_temp_task[$val['nns_id']]=$val['nns_ref_id'];
		        }
		        $arr_group_playbill_info = nl_playbill::query_by_ids($obj_dc, array_values($arr_temp_task));
		        if($arr_group_playbill_info['ret']!=0 || !isset($arr_group_playbill_info['data_info']) || empty($arr_group_playbill_info['data_info']) || !is_array($arr_group_playbill_info['data_info']))
		        {
		            continue;
		        }
		        $str_xml  ='<?xml version="1.0" encoding="UTF-8"?>';
		        $str_xml .='<ADI xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" BizDomain="' . $int_bizdomain . '" Priority="1">';
		        $str_xml .=   '<Objects>';
		        foreach ($arr_group_playbill_info['data_info'] as $playbill_value)
		        {
		            // 组装C2注入的节目单工单xml信息
		            $int_begin_time = strtotime($playbill_value['nns_begin_time']);
		            $str_start_date = date('Ymd', $int_begin_time);
		            $str_start_time = date('His', $int_begin_time);
		            $str_duration = date('His', strtotime('today') + $playbill_value['nns_time_len']);
		            $arr_playbill_import_info = public_model_exec::get_asset_id_by_sp_id($sp_id, 'playbill', $playbill_value['nns_id'], $playbill_value);
		            if ($arr_playbill_import_info['ret'] != 0 || !isset($arr_playbill_import_info['data_info']) || strlen($arr_playbill_import_info['data_info']) == 0)
		            {
		                return false;
		            }
// 		            $str_Action = ($playbill_value['nns_state'] !=1) ? ($playbill_value['nns_modify_time'] > $playbill_value['nns_create_time']) ? 'REGIST' : 'REGIST' : 'DELETE';
		            $str_Action = ($i==0) ? 'DELETE' : 'REGIST';
		            $str_xml .='<Object ElementType="Schedule" ID="' . $arr_playbill_import_info['data_info'] . '" Action="' . $str_Action . '" Code="' . $arr_playbill_import_info['data_info'] . '">';
		            $str_xml .=   '<Property Name="ChannelCode">' . $arr_live_import_info['data_info'] . '</Property>';
		            $str_xml .=   '<Property Name="ChannelID">' . $arr_live_import_info['data_info'] . '</Property>';
		            $str_xml .=   '<Property Name="ProgramName">' . $playbill_value['nns_name'] . '</Property>';
		            $str_xml .=   '<Property Name="StartDate">' . $str_start_date . '</Property>';
		            $str_xml .=   '<Property Name="StartTime">' . $str_start_time . '</Property>';
		            $str_xml .=   '<Property Name="Duration">' . $str_duration . '</Property>';
		            $str_xml .=   '<Property Name="StorageDuration"></Property>';
		            $str_xml .=   '<Property Name="Status">1</Property>';
		            $str_xml .=   '<Property Name="Description">' . $playbill_value['nns_summary'] . '</Property>';
		            $str_xml .=   '<Property Name="Genre"></Property>';
		            $str_xml .='</Object>';
		        }
		        $str_xml .=   '</Objects>';
		        $str_xml .='</ADI>';
		        
		        // 组装C2注入数据
		        $str_file_name = $sp_id . '_cms_' . date('YmdHis') . '_' . rand(1000, 9999) . '_' . 'playbill' . '_' . $action . '_' .  rand(100, 999) . '.xml';
		        $arr_c2_info = array(
		            'nns_task_type' => 'Schedule',
		            'nns_task_id'   => $item['nns_task_id'],
		            'nns_task_name' => $item['bk_c2_task_info']['nns_name'],
		            'nns_action'    => $action,
		            'nns_url'       => $str_file_name,
		            'nns_content'   => $str_xml,
		            'nns_desc'      => 'Schedule' . $action,
		            'nns_ex_group'  => (is_array($arr_temp_task) && !empty($arr_temp_task)) ? json_encode(array_keys($arr_temp_task)) : '',
		        );
		        
		        // C2注入
		        $result =  self::execute_c2($arr_c2_info, $sp_id);
		        if(is_array($arr_temp_task) && !empty($arr_temp_task))
		        {
		            $arr_temp_task_keys = array_keys($arr_temp_task);
		            $str_date = date("Y-m-d H:i:s");
		            if(true === $result)
		            {
		                nl_execute_by_db("update nns_mgtvbk_c2_task set nns_status=5,nns_modify_time='{$str_date}',nns_epg_status=97 where nns_id in('".implode("','", $arr_temp_task_keys)."')", $obj_dc->db());
		            }
		            else
		            {
		                nl_execute_by_db("update nns_mgtvbk_c2_task set nns_modify_time='{$str_date}',nns_epg_status=97,nns_cdn_fail_time=nns_cdn_fail_time+1 where nns_id in('".implode("','", $arr_temp_task_keys)."')", $obj_dc->db());
		            }
		        }
		        sleep(5);
		    }
		    return $result;
		}
		else
		{
            // 组装C2注入的节目单工单xml信息
            $int_begin_time = strtotime($arr_playbill_info['nns_begin_time']);
            $str_start_date = date('Ymd', $int_begin_time);
            $str_start_time = date('His', $int_begin_time);
            $str_duration = date('His', strtotime('today') + $arr_playbill_info['nns_time_len']);
            $str_xml = '<?xml version="1.0" encoding="UTF-8"?>';
            $str_xml .= '<ADI xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" BizDomain="' . $int_bizdomain . '" Priority="1">';
            $str_xml .= '<Objects>';
            $str_xml .= '<Object ElementType="Schedule" ID="' . $arr_playbill_import_info['data_info'] . '" Action="' . $action . '" Code="' . $arr_playbill_import_info['data_info'] . '">';
            $str_xml .= '<Property Name="ChannelCode">' . $arr_live_import_info['data_info'] . '</Property>';
            $str_xml .= '<Property Name="ChannelID">' . $arr_live_import_info['data_info'] . '</Property>';
            $str_xml .= '<Property Name="ProgramName">' . $arr_playbill_info['nns_name'] . '</Property>';
            $str_xml .= '<Property Name="StartDate">' . $str_start_date . '</Property>';
            $str_xml .= '<Property Name="StartTime">' . $str_start_time . '</Property>';
            $str_xml .= '<Property Name="Duration">' . $str_duration . '</Property>';
            $str_xml .= '<Property Name="StorageDuration"></Property>';
            $str_xml .= '<Property Name="Status">1</Property>';
            $str_xml .= '<Property Name="Description">' . $arr_playbill_info['nns_summary'] . '</Property>';
            $str_xml .= '<Property Name="Genre"></Property>';
            $str_xml .= '</Object>';
            $str_xml .= '</Objects>';
            $str_xml .= '</ADI>';
		}

        // 组装C2注入数据
        $str_file_name = $sp_id . '_cms_' . date('YmdHis') . '_' . rand(1000, 9999) . '_' . 'playbill' . '_' . $action . '_' .  rand(100, 999) . '.xml';
        $arr_c2_info = array(
            'nns_task_type' => 'Schedule',
            'nns_task_id'   => $item['nns_task_id'],
            'nns_task_name' => $item['bk_c2_task_info']['nns_name'],
            'nns_action'    => $action,
            'nns_url'       => $str_file_name,
            'nns_content'   => $str_xml,
            'nns_desc'      => 'Schedule' . $action,
            'nns_ex_group'  => (is_array($arr_temp_task) && !empty($arr_temp_task)) ? json_encode(array_keys($arr_temp_task)) : '',
        );

        // C2注入
        $result =  self::execute_c2($arr_c2_info, $sp_id);
        if(is_array($arr_temp_task) && !empty($arr_temp_task))
        {
            $arr_temp_task_keys = array_keys($arr_temp_task);
            $str_date = date("Y-m-d H:i:s");
            if(true === $result)
            {
                nl_execute_by_db("update nns_mgtvbk_c2_task set nns_status=5,nns_modify_time='{$str_date}',nns_epg_status=97 where nns_id in('".implode("','", $arr_temp_task_keys)."')", $obj_dc->db());
            }
            else
            {
                nl_execute_by_db("update nns_mgtvbk_c2_task set nns_modify_time='{$str_date}',nns_epg_status=97,nns_cdn_fail_time=nns_cdn_fail_time+1 where nns_id in('".implode("','", $arr_temp_task_keys)."')", $obj_dc->db());
            }
        }
        return $result;
    }
	
	
	static public function update_playbill($playbill){
		$action = 'UPDATE';
		//
		return self::do_playbill($playbill,$action);
	}

	static public function delete_playbill($playbill){
		$action = 'DELETE';
		//
		return self::do_delete_playbill($playbill,$action);
	}

	/**
	 * params 
	 */
	static public function do_delete_playbill($params){
		$action = 'DELETE';
		$playbill_id = $params['nns_id'];
		//return self::do_movie($media,$action);
		$xml_str = '<?xml version="1.0" encoding="UTF-8"?><ADI xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" BizDomain="2" Priority="1">';
		$xml_str .= '<Objects>';
		$xml_str .= '<Object ElementType="Schedule" ID="' .$playbill_id. '" Action="' . $action . '" Code="' .$playbill_id. '">';	
		$xml_str .= '</Object>';
		$xml_str .= '</Objects>';
		$xml_str .= '</ADI>';

		$time = date('YmdHis') . rand(0, 10000);
		$three_rand = rand(100, 999);
		$file_name = 'zgcms_'. $time .'_' . 'schedule' .'_'. $action . '_' . $three_rand. '.xml';

		$c2_info = array(
		//'nns_id' => $c2_info['c2_id'],
		'nns_task_type'=>'Schedule',
		'nns_task_id'=> isset($params['nns_task_id'])?$params['nns_task_id']:null,
		'nns_task_name'=> isset($params['nns_task_name'])?$params['nns_task_name']:null,
		'nns_action'=>	$action,
		'nns_url' => $file_name,
		'nns_content' => $xml_str,
		//'nns_result' =>  '['.$result['ret'].']'.$result['desc'],
		'nns_desc' => 'Schedule,'.$action,
		);		
		return self::execute_c2($c2_info);
	}

	static public function do_playbill($playbill,$action){
		$xml_str = '<?xml version="1.0" encoding="UTF-8"?><ADI xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" BizDomain="2" Priority="1">';
		$xml_str .= '<Objects>';

		$xml_str .= '<Object ElementType="Schedule" ID="' .$playbill['nns_id']. '" Action="' . $action . '" Code="' .$playbill['nns_id']. '">';	
		$xml_str .= '<Property Name="ChannelID"></Property>';
		$xml_str .= '<Property Name="ChannelCode"></Property>';
		$xml_str .= '<Property Name="ProgramName"></Property>';

		$xml_str .= '<Property Name="SearchName"></Property>';
		$xml_str .= '<Property Name="Genre"></Property>';
		$xml_str .= '<Property Name="SourceType"></Property>';	
		$xml_str .= '<Property Name="StartDate"></Property>';
		$xml_str .= '<Property Name="StartTime"></Property>';
		$xml_str .= '<Property Name="Duration"></Property>';
		$xml_str .= '<Property Name="Status">1</Property>';
		$xml_str .= '<Property Name="Description"></Property>';		
		
		$xml_str .= '<Property Name="ObjectType"></Property>';
		$xml_str .= '<Property Name="ObjectCode"></Property>';

		$xml_str .= '</Object>';
		/*
		$xml_str .= '<Mappings>';
		
		$xml_str .= '<Mapping ParentType="Program" ParentID="'.$vod_api_id.'" ElementType="Movie" ElementID="'.$media_api_id.'" ParentCode="'.$nns_vod_id.'" ElementCode="'.$nns_media_id.'" Action="'.$action.'">';
		$xml_str .= '</Mapping>';
			
		$xml_str .= '</Mappings>';
		*/
		$xml_str .= '</Objects>';
		$xml_str .= '</ADI>';

		$time = date('YmdHis') . rand(0, 10000);
		$three_rand = rand(100, 999);
		$file_name = 'zgcms_'. $time .'_' . 'schedule' .'_'. $action . '_' . $three_rand. '.xml';
		
		
		$c2_info = array(
		//'nns_id' => $c2_info['c2_id'],
		'nns_task_type'=>'Schedule',
		'nns_task_id'=> isset($playbill['nns_task_id'])?$playbill['nns_task_id']:null,
		'nns_task_name'=> isset($playbill['nns_task_name'])?$playbill['nns_task_name']:null,		
		'nns_action'=>	$action,
		'nns_url' => $file_name,
		'nns_content' => $xml_str,
		//'nns_result' =>$result,
		'nns_desc' => 'Schedule,'.$action,
		);

		return self::execute_c2($c2_info);
	}

	/**
	 * 直播源
	 */
	static public function add_live_media($params,$action,$live_id,$live_name,$sp_id){
		$xml_str = '<?xml version="1.0" encoding="UTF-8"?><ADI xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" BizDomain="2" Priority="1">';
		$xml_str .= '<Objects>';
		if(is_array($params) && count($params)>0){
			foreach ($params as $live_media) {
				$xml_str .= '<Object ElementType="PhysicalChannel" ID="' .$live_media['nns_id']. '" Action="' . $action . '" Code="' .$live_media['nns_id']. '">';	
				$xml_str .= '<Property Name="ChannelID">'.$live_media['nns_live_id'].'</Property>';//频道ID
				$xml_str .= '<Property Name="ChannelCode">'.$live_media['nns_live_id'].'</Property>';//频道Code
				//$xml_str .= '<Property Name="BitRateType">'.$live_media['nns_kbps'].'</Property>';//码流2: 2M 4: 4M		
				
				if(strtoupper($live_media['nns_mode'])=="HD"){
					$xml_str .= '<Property Name="BitRateType">4</Property>';//码流2: 2M 4: 4M	
				}else{
					$xml_str .= '<Property Name="BitRateType">2</Property>';//码流2: 2M 4: 4M	
				}
				
				$xml_str .= '<Property Name="MultiCastIP">239.111.111.111</Property>';
				$xml_str .= '<Property Name="MultiCastPort">4001</Property>';
				$xml_str .= '<Property Name="BitrateCount">1</Property>';
				$xml_str .= '</Object>';
			}				
		}
		$xml_str .= '</Objects>';
		$xml_str .= '</ADI>';

		$time = date('YmdHis') . rand(0, 10000);
		$three_rand = rand(100, 999);
		$file_name = 'zgcms_'. $time .'_' . 'live_media' .'_'. $action . '_' . $three_rand. '.xml';

		$c2_info = array(
		//'nns_id' => $c2_info['c2_id'],
		'nns_task_type'=>'PhysicalChannel',
		'nns_task_id'=> isset($params['nns_task_id'])?$params['nns_task_id']:null,
		'nns_task_name'=> isset($params['nns_task_name'])?$params['nns_task_name']:$live_name.'-直播流',	
		'nns_action'=>	$action,
		'nns_url' => $file_name,
		'nns_content' => $xml_str,
		//'nns_result' =>$result,
		'nns_desc' => 'PhysicalChannel,'.$action,
		);

		return self::execute_c2($c2_info,$sp_id);
	}
	
	
	/**
	 * 直播源
	 */
	static public function add_live_media_v2($params,$action,$live_id,$live_name,$sp_id){
		$xml_str = '<?xml version="1.0" encoding="UTF-8"?><ADI xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" BizDomain="2" Priority="1">';
		$xml_str .= '<Objects>';
		if(is_array($params) && count($params)>0){
			foreach ($params as $live_media) {
				$xml_str .= '<Object ElementType="PhysicalChannel" PhysicalContentID="' .$live_media['nns_id']. '" Action="' . $action . '" Code="' .$live_media['nns_id']. '">';
				$xml_str .= '<Property Name="ChannelID">'.$live_media['nns_live_id'].'</Property>';//频道ID
				if(strtoupper($live_media['nns_mode'])=="HD"){
					$xml_str .= '<Property Name="BitRateType">4</Property>';//码流2: 2M 4: 4M
				}else{
					$xml_str .= '<Property Name="BitRateType">2</Property>';//码流2: 2M 4: 4M
				}
				
				
				
				if($live_media['nns_cast_type'] == 1)
				{
					$temp_url = $live_media['nns_url'];
					$arr_temp_url = explode(':', trim($temp_url));
					if(count($arr_temp_url) == 2)
					{
						$temp_url_1 = ltrim($arr_temp_url[0],'@');
						$temp_url_2 = $arr_temp_url[1];
					}
					else
					{
						$temp_url_1 = ltrim($arr_temp_url[1],'//@');
						$temp_url_2 = $arr_temp_url[2];
					}
					$xml_str .= '<Property Name="DestCastType">multicast</Property>';
					$xml_str .= '<Property Name="SrcCastType">multicast</Property>';
					$xml_str .= '<Property Name="MultiCastIP">'.$temp_url_1.'</Property>';
					$xml_str .= '<Property Name="MultiCastPort">'.$temp_url_2.'</Property>';
				}
				else
				{
					$xml_str .= '<Property Name="DestCastType">unicast</Property>';
					$xml_str .= '<Property Name="SrcCastType">unicast</Property>';
					$xml_str .= '<Property Name="UnicastUrl">'.$live_media['nns_url'].'</Property>';
				}

				$xml_str .= '<Property Name="CPContentID">'.$live_media['nns_id'].'</Property>';//频道ID
				$xml_str .= '<Property Name="VideoType">8</Property>';
				$xml_str .= '<Property Name="AudioType"></Property>';
				$xml_str .= '<Property Name="Resolution"></Property>';
				$xml_str .= '<Property Name="Video_Profile"></Property>';
				$xml_str .= '<Property Name="System_Layer"></Property>';
				if($live_media['nns_cast_type'] == 1)
				{
					$xml_str .= '<Property Name="Domain">257</Property>';
				}
				else
				{
					$xml_str .= '<Property Name="Domain">264</Property>';
				}
				$xml_str .= '<Property Name="Hotdegree"></Property>';
				$xml_str .= '<Property Name="TimeShift">1</Property>';
				$xml_str .= '<Property Name="TimeShiftDuration">180</Property>';
				$xml_str .= '<Property Name="TvodStatus">1</Property>';
				$xml_str .= '<Property Name="StorageDuration">1</Property>';
				$xml_str .= '</Object>';
			}
		}
		$xml_str .= '</Objects>';
		$xml_str .= '</ADI>';
	
		$time = date('YmdHis') . rand(0, 10000);
		$three_rand = rand(100, 999);
		$file_name = 'zgcms_'. $time .'_' . 'live_media' .'_'. $action . '_' . $three_rand. '.xml';
	
		$c2_info = array(
				//'nns_id' => $c2_info['c2_id'],
				'nns_task_type'=>'PhysicalChannel',
				'nns_task_id'=> isset($params['nns_task_id'])?$params['nns_task_id']:null,
				'nns_task_name'=> isset($params['nns_task_name'])?$params['nns_task_name']:$live_name.'-直播流',
				'nns_action'=>	$action,
				'nns_url' => $file_name,
				'nns_content' => $xml_str,
				//'nns_result' =>$result,
				'nns_desc' => 'PhysicalChannel,'.$action,
		);
	
		return self::execute_c2($c2_info,$sp_id);
	}
	/**
	 * @params array(
	 * nns_id
	 * nns_task_id
	 * )
	 */
	static public function delete_live_media($params,$action,$sp_id){
		//$action = 'REGIST';
		$xml_str = '<?xml version="1.0" encoding="UTF-8"?><ADI xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" BizDomain="2" Priority="1">';
		$xml_str .= '<Objects>';	
		$xml_str .= '<Object ElementType="PhysicalChannel" ID="' .$params['nns_id']. '" Action="' . $action . '" Code="' .$params['nns_id']. '">';	
		$xml_str .= '</Object>';
		$xml_str .= '</Objects>';
		$xml_str .= '</ADI>';

		$time = date('YmdHis') . rand(0, 10000);
		$three_rand = rand(100, 999);
		$file_name = 'zgcms_'. $time .'_' . 'live_media' .'_'. $action . '_' . $three_rand. '.xml';

		$c2_info = array(
		//'nns_id' => $c2_info['c2_id'],
		'nns_task_type'=>'PhysicalChannel',
		'nns_task_id'=> isset($params['nns_task_id'])?$params['nns_task_id']:null,	
		'nns_task_name'=> isset($params['nns_task_name'])?$params['nns_task_name']:null,
		'nns_action'=>	$action,
		'nns_url' => $file_name,
		'nns_content' => $xml_str,
		//'nns_result' =>$result,
		'nns_desc' => 'PhysicalChannel,'.$action,
		);

		return self::execute_c2($c2_info,$sp_id);
	}

	static public function do_content_query($task_info,$sp_id){
		$xml_str = '<?xml version="1.0" encoding="UTF-8"?><ADI xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" BizDomain="2" Priority="1">';
		$xml_str .= '<Objects>';
		$xml_str .= '<Object ElementType="ContentQuery" ID="' .$task_info['nns_ref_id']. '"  Code="' .$task_info['nns_ref_id']. '">';
		$xml_str .= '<Property Name="ObjectType">Movie</Property>';
		$xml_str .= '</Object>';
		$xml_str .= '</Objects>';
		$xml_str .= '</ADI>';
		$guid =  np_guid_rand();

		$time = date('YmdHis') . rand(0, 10000);
		$three_rand = rand(100, 999);
		$file_name = 'zgcms_'. $time .'_' . 'content_query' .'_'. $action . '_' . $three_rand. '.xml';

		$action = 'REGIST';
		$c2_info = array(
		'nns_task_type'=>'QueryPlay',
		'nns_task_id'=> $task_info['nns_id'],
		'nns_task_name'=> $task_info['nns_name'],
		'nns_action'=>	$action,
		'nns_url' => $file_name,
		'nns_content' => $xml_str,
		'nns_desc' => 'QueryPlay,'.$action,
		);
		return self::execute_c2($c2_info,$sp_id);
	}

	/**
	 * 华为没有处理的指令，再次重发
	 */
	static public function resend_c2_again($sp_id){
		$db = nn_get_db(NL_DB_READ);
		/************超时没返回重发************/
		$time_out = 3600;
		$sql = "select * from nns_mgtvbk_c2_log where nns_org_id='$sp_id' and nns_again=0 and nns_create_time < NOW() - INTERVAL ".$time_out." SECOND  and nns_notify_result is null  order by nns_create_time asc  limit 90";
		$all = nl_db_get_all($sql,$db);	
		if(is_array($all)) {
			foreach($all as $item0){
				self::execute_c2_again($item0['nns_id'],$sp_id);
			}			
		}
		
		/************以下为失败重发************/
		//连续剧
		$sql = "select * from nns_mgtvbk_c2_log where nns_org_id='$sp_id' and	(nns_notify_result='-1' and (nns_notify_result_url=''  or nns_notify_content like '%Entity queue is full%') or nns_result like '%[-1]soap info is full%') and nns_again=0 order by nns_again asc,nns_create_time asc  limit 90";
		$all = nl_db_get_all($sql,$db);
		if(is_array($all)) {
			foreach($all as $item0){
				self::execute_c2_again($item0['nns_id'],$sp_id);
			}
		}
	}

	static public function execute_c2_again($nns_id,$sp_id){
		$db = nn_get_db(NL_DB_READ);
		$db_w = nn_get_db(NL_DB_WRITE);
		$sql = "select * from nns_mgtvbk_c2_log where nns_id='$nns_id'";
		$c2_info = nl_db_get_one($sql,$db);
		
		/*$count = "select count(1) as num from nns_mgtvbk_c2_log where nns_org_id='{$sp_id}' and nns_task_id='{$c2_info['nns_task_id']}' and nns_task_type='{$c2_info['nns_task_type']}'";
		$c = nl_db_get_col($count, $db);
		if($c>=2){
			return false;
		}*/
		// include_once dirname(dirname(dirname(__FILE__))).'/mgtv/'.$sp_id.'/'.$sp_id.'_client.php';
		// $CmdFileURL = C2_FTP.$c2_info['nns_url'];
		// $c2_info['nns_id'] = np_guid_rand();
		// $c2_info['nns_again'] = 0;
		// unset($c2_info['nns_result'],$c2_info['nns_notify_result_url'],$c2_info['nns_notify_result'],$c2_info['nns_notify_time'],$c2_info['nns_modify_time'],$c2_info['nns_notify_content']);
		// $dt = date('Y-m-d H:i:s');
		// $c2_info['nns_create_time'] = $dt;
		// $c2_info['nns_send_time'] = $dt;
		// $result = call_user_func_array(array($sp_id.'_client', 'ExecCmd'), array($c2_info['nns_id'], $CmdFileURL));
		// $c2_info['nns_result'] = '['.$result->Result.']'.$result->ErrorDescription;
		//$result = jllt_client::ExecCmd($nns_id,$CmdFileURL);
		$arr_sp_config = sp_model::get_sp_config($c2_info['nns_org_id']);
		if(isset($arr_sp_config['playbill']['enabled']) && $arr_sp_config['playbill']['enabled'] == '1' && isset($c2_info['nns_ex_group']) && strlen($c2_info['nns_ex_group']) >0)
		{
		    $nns_ex_group = json_decode($c2_info['nns_ex_group'],true);
		    if(is_array($nns_ex_group) && !empty($nns_ex_group))
		    {
		        $sql = "update nns_mgtvbk_c2_task set nns_status=1 ,nns_modify_time=now() where nns_id in ('".implode("','", $nns_ex_group)."')";
		        nl_execute_by_db($sql,$db_w);
		    }
		}
		$sql = "update nns_mgtvbk_c2_log set nns_again=1 ,nns_notify_result='-1',nns_modify_time=now() where nns_id='".$nns_id."'";
		nl_execute_by_db($sql,$db_w);
		
		if($c2_info['nns_task_id']){
			content_task_model::vod($c2_info['nns_task_id'],null,$sp_id);
		}

		return true;
	}
	/**
	 * 执行C2注入命令
	 * @param $c2_info array(
	 * 'c2_id'
	 * 'file_name'
	 * 'xml_content'
	 * )
	 */
	static public function execute_c2($c2_info,$sp_id){
		global $g_webdir;
		if($sp_id == 'ZTE_CDN')
		{
			$c2_id = np_guid_rand_v2();
		}
		else
		{
			$c2_id = np_guid_rand();
		}
		$c2_info['nns_id'] = $c2_id;
		if(file_exists(dirname(dirname(__FILE__)).'/'.$sp_id.'/models/child_c2_task_model.php')){
			include_once dirname(dirname(__FILE__)).'/'.$sp_id.'/models/child_c2_task_model.php';	
			if(method_exists('child_c2_task_model','execute_c2')){
				$re = child_c2_task_model::execute_c2($c2_info,$sp_id);
				return $re;
			}
		}		
		include_once dirname(dirname(dirname(__FILE__))).'/mgtv/'.$sp_id.'/'.$sp_id.'_client.php';
		if(!self::exists_c2_commond($c2_info,$sp_id)){
		$sub_path = date('Y-m-d');
		$file = $c2_info['nns_url'];
		$c2_info['nns_url'] = $sub_path.'/'.$file;
		$xml_str = $c2_info['nns_content'];
		$file_path = dirname(dirname(dirname(__FILE__))).'/data/mgtv/'.$sp_id.'/inject_xml/'.$sub_path.'/';
		if(!is_dir($file_path)) mkdir($file_path,0777,true);
		$file_path .= $file;
		file_put_contents($file_path,$xml_str);
		$CmdFileURL = C2_FTP.$c2_info['nns_url'];
		try {
			np_runtime_ex($c2_id,false); 
			DEBUG && i_write_log_core('---------execute c2----------'.var_export($c2_info,true),'soap');			
			$result = call_user_func_array(array($sp_id.'_client', 'ExecCmd'), array($c2_id, $CmdFileURL));
			/*$c2_info['nns_result'] = '['.$result->Result.']';//$result->ErrorDescription;
			$bool = false;
			if($result->Result != 0 ){
			*/
			
			$result = isset($result->Result) ? $result->Result : $result->result;
			$result = ($result === null) ? 0 : $result;
			$c2_info['nns_result'] = '['.$result.']';//$result->ErrorDescription;
			$bool = false;
			if($result != 0 ){
				//$c2_info['nns_notify_result'] = -1;
				$bool = true;
			}
			DEBUG && i_write_log_core('---------execute soap time----------'.np_runtime_ex($c2_id,true),'soap');
			self::save_c2_log($c2_info,$sp_id);
			
			if($bool===true){
                            $c2_info['nns_result'] .= '注入CDN失败';
			    self::execute_c2_notify(false, $sp_id, $c2_info);
				return false;
			}
            $c2_info['nns_result'] .= '注入CDN成功';
            self::execute_c2_notify(true, $sp_id, $c2_info);
			return true;
		} catch (Exception $e) {
                $c2_info['nns_result'] = '[-1] 注入CDN失败，抛出异常:' . var_export($e, true);
                $c2_info['nns_notify_result'] = -1;
			self::save_c2_log($c2_info,$sp_id);
            self::execute_c2_notify(false, $sp_id, $c2_info);
			return false;
		}
		}
		$c2_info['nns_result'] = '[-1] 注入失败，有相同任务正在CDN注入中, 请稍后再操作';
		$c2_info['nns_notify_result'] = -1;
        self::execute_c2_notify(false, $sp_id, $c2_info);
		return false;
	}

    /**
     * @description:消息反馈给芒果二级
     * @author:xinxin.deng
     * @date: 2018/1/19 10:06
     * @param $bool
     * @param $sp_id
     * @param $c2_info
     */
	static public function execute_c2_notify($bool, $sp_id, $c2_info)
    {
        $state = $bool === true ? 1 : 0;
        // 创建DC对象
        $obj_dc = nl_get_dc(array (
            'db_policy'     => NL_DB_WRITE|NL_DB_READ,
            'cache_policy'  => NP_KV_CACHE_TYPE_MEMCACHE
        ));
        $sp_config = sp_model::get_sp_config($sp_id);
       $sql = "select nns_message_id,nns_ref_id from nns_mgtvbk_c2_task where nns_id='".$c2_info['nns_task_id']."'";
        $arr_message_id = nl_db_get_one($sql,$obj_dc->db());
        $c2_info['nns_message_id'] = $arr_message_id['nns_message_id'];
        $c2_info['nns_ref_id'] = $arr_message_id['nns_ref_id'];
        $flag_message_feedback_enabled = (!isset($sp_config['message_feedback_enabled']) || $sp_config['message_feedback_enabled'] !=1) ? true : false;
        if(!$flag_message_feedback_enabled || !isset($sp_config['message_feedback_mode']) || $sp_config['message_feedback_mode'] != 0)
        {
            self::__debug('不允许反馈或者反馈模式不正确：
            [message_feedback_enabled]=' . $sp_config['message_feedback_enabled'] . 'message_feedback_mode=' . $sp_config['message_feedback_mode']);
            return;
        }
        $cdn_id = '';
        $mg_asset_type = '';
        $mg_asset_id = '';
        $mg_part_id = '';
        $mg_file_id = '';
        if($c2_info['nns_task_type'] == 'Series')
        {
            $vod_sql = "select nns_integer_id,nns_asset_import_id from nns_vod where nns_id='{$c2_info['nns_ref_id']}'";
            $video_info = nl_query_by_db($vod_sql, $obj_dc->db());
            $mg_asset_type = 1;
            $mg_asset_id = $video_info[0]['nns_asset_import_id'];
            switch ($sp_config['import_id_mode'])
            {
                case '1':
                    $cdn_id = '000000'.$video_info[0]['nns_integer_id'];
                    $cdn_id = str_pad($cdn_id,32,"0");
                    break;
                case '2':
                    $cdn_id = $video_info[0]['nns_asset_import_id'];
                    break;
                case '3':
                    $cdn_id = CSP_ID . '0001' . $video_info[0]['nns_integer_id'];
                    $cdn_id = str_pad($cdn_id,32,"0");
                    break;
                case '4':
                    $arr_csp_id = explode("|", CSP_ID);
                    $str_lenth = strlen($arr_csp_id[0])+strlen($arr_csp_id[1])+1;
                    $lest_num = 32-$str_lenth;
                    $cdn_id = $arr_csp_id[0].'1'.str_pad($video_info[0]['nns_integer_id'], $lest_num, "0", STR_PAD_LEFT).$arr_csp_id[1];
                    break;
                default:
                    $cdn_id = $c2_info['nns_ref_id'];
                    break;
            }
        }
        if($c2_info['nns_task_type'] == 'Program')
        {
            $index_sql = "select nns_integer_id,nns_import_id from nns_vod_index where nns_id='{$c2_info['nns_ref_id']}'";
            $index_info = nl_query_by_db($index_sql, $obj_dc->db());
            if(is_array($index_info))
            {
                $mg_part_id = $index_info[0]['nns_import_id'];
                $vod_sql = "select nns_integer_id,nns_asset_import_id from nns_vod where nns_id='{$index_info[0]['nns_vod_id']}'";
                $video_info = nl_query_by_db($vod_sql, $obj_dc->db());
                $mg_asset_id = $video_info[0]['nns_asset_import_id'];

                switch ($sp_config['import_id_mode'])
                {
                    case '1':
                        $cdn_id = '001000'.$index_info[0]['nns_integer_id'];
                        $cdn_id = str_pad($cdn_id,32,"0");
                        break;
                    case '2':
                        $cdn_id = $index_info[0]['nns_import_id'];
                        break;
                    case '3':
                        $cdn_id = CSP_ID . '0002' . $index_info[0]['nns_integer_id'];
                        $cdn_id = str_pad($cdn_id,32,"0");
                        break;
                    case '4':
                        $arr_csp_id = explode("|", CSP_ID);
                        $str_lenth = strlen($arr_csp_id[0])+strlen($arr_csp_id[1])+1;
                        $lest_num = 32-$str_lenth;
                        $cdn_id = $arr_csp_id[0].'1'.str_pad($index_info[0]['nns_integer_id'], $lest_num, "0", STR_PAD_LEFT).$arr_csp_id[1];
                        break;
                    default:
                        $cdn_id = $c2_info['nns_ref_id'];
                        break;
                }
            }
            $mg_asset_type = 2;
        }
        //如果是片源,则查询片源的文件时长和文件大小
        if($c2_info['nns_task_type'] == 'Movie')
        {
            $media_sql = "select nns_file_size,nns_file_time_len,nns_import_id,nns_integer_id,nns_content_id,nns_url from nns_vod_media where nns_id='{$c2_info['nns_ref_id']}'";
            $media_info = nl_query_by_db($media_sql, $obj_dc->db());
            if(is_array($media_info))
                {
                    $nns_file_size = $media_info[0]['nns_file_size'];
                    $nns_file_time_len = $media_info[0]['nns_file_time_len'];
                    $item['nns_file_len'] = $nns_file_time_len;
                    $item['nns_file_size'] = $nns_file_size;

                    $mg_file_id = $media_info[0]['nns_import_id'];

                    //获取所属主媒资注入id
                    $vod_sql = "select nns_integer_id,nns_asset_import_id from nns_vod where nns_id='{$media_info[0]['nns_vod_id']}'";
                    $video_info = nl_query_by_db($vod_sql, $obj_dc->db());
                    $mg_asset_id = $video_info[0]['nns_asset_import_id'];

                    //获取所属分集注入id
                    $index_sql = "select nns_integer_id,nns_import_id from nns_vod_index where nns_id='{$media_info[0]['nns_vod_index_id']}'";
                    $index_info = nl_query_by_db($index_sql, $obj_dc->db());
                    $mg_part_id = $index_info[0]['nns_import_id'];

                    switch ($sp_config['import_id_mode'])
                    {
                        case '1':
                            $cdn_id = '002000'.$media_info[0]['nns_integer_id'];
                            $cdn_id = str_pad($cdn_id,32,"0");
                            break;
                        case '2':
                            $cdn_id = $media_info[0]['nns_import_id'];
                            break;
                        case '3':
                            $cdn_id = CSP_ID . '0003' . $media_info[0]['nns_integer_id'];
                            $cdn_id = str_pad($cdn_id,32,"0");
                            break;
                        case '4':
                            $arr_csp_id = explode("|", CSP_ID);
                            $str_lenth = strlen($arr_csp_id[0])+strlen($arr_csp_id[1])+1;
                            $lest_num = 32-$str_lenth;
                            $cdn_id = $arr_csp_id[0].'1'.str_pad($media_info[0]['nns_integer_id'], $lest_num, "0", STR_PAD_LEFT).$arr_csp_id[1];
                            break;
                        default:
                            $cdn_id = $c2_info['nns_ref_id'];
                            break;
                    }
                }
            $mg_asset_type = 3;
        }
        //查询sp的上报地址/芒果使用站点ID
        if(isset($sp_config['site_id'])&&strlen($sp_config['site_id'])>0&&isset($sp_config['site_callback_url'])&&strlen($sp_config['site_callback_url'])>0)
        {
            //湖南电信添加HW/ZTE标识反馈
            if($sp_id == 'hndx')
            {
                $cp_id='ZTE';
            }
            else if ($sp_id == 'hndx_hw')
            {
                $cp_id='HW';
            }
            else
            {
                $cp_id ='';
            }
            $xml_info = array(
                'msgid' => $c2_info['nns_message_id'],
                'state' => $state,
                'msg' => $c2_info['nns_result'],
                'info' => array(
                    'cdn_id' => $cdn_id,
                    'site_id' => $sp_config['site_id'],
                    'cp_id' => $cp_id,
                    'mg_asset_type' => $mg_asset_type,
                    'mg_asset_id' => $mg_asset_id,
                    'mg_part_id' => $mg_part_id,
                    'mg_file_id' => $mg_file_id,
                ),
            );
            $xml = self::_build_notify($xml_info);
            $data = array(
                'cmsresult'=>$xml,
            );
            self::__debug(var_export($sp_config['site_callback_url'],true));
            self::__debug(var_export($data,true));

            $http_curl = new np_http_curl_class();
            for ($i = 0; $i < 3; $i++) {
                //访问媒资注入接口
                $re = $http_curl->post($sp_config['site_callback_url'],$data,null,2);
                $curl_info = $http_curl->curl_getinfo();
                $http_code = $curl_info['http_code'];
                self::__debug('返回状态'.var_export($http_code,true));
                self::__debug(var_export($curl_info,true));
                self::__debug(var_export($re,true));
                if ($http_code != 200 && (int)$re === 1) {
                    continue;
                } else {
                    break;
                }
            }
        }
        return;
    }

    static public function __write_log($msg,$deep='error'){
        $debug_log =new np_log_class();
        $debug_log->set_path(dirname(dirname(dirname(__FILE__))).'/data/log/op_queue/'.$deep.'/');
        $debug_log->write($msg);
    }

    static public function __debug($msg){
        self::__write_log($msg,'debug');
    }

    /**
     * 组装反馈的XML
     * @param $params
     * @return string|void
     */
    static public function _build_notify($params)
    {
        if(!is_array($params) || empty($params))
        {
            return ;
        }
        $dom = new DOMDocument('1.0', 'utf-8');
        $xmlresult = $dom->createElement('xmlresult');
        $dom->appendChild($xmlresult);
        foreach ($params as $key=>$value)
        {
            $$key = $dom->createElement($key);
            $xmlresult->appendchild($$key);
            if(!empty($value) && is_array($value))
            {
                foreach ($value as $k=>$val)
                {
                    $$k = $dom->createElement($k);
                    $$key->appendchild($$k);
                    //创建元素值
                    $content = $dom->createTextNode($val);
                    $$k->appendchild($content);
                }
            }
            else
            {
                //创建元素值
                $text = $dom->createTextNode($value);
                $$key->appendchild($text);
            }
        }
        return $dom->saveXML();
    }

	static public function exists_c2_commond($c2_info,$sp_id){
        return false;//只是福建移动在用，其他项目关闭 xinxin.deng 2018/4/27 16:52
		set_time_limit(0);
		$db_r = nn_get_db(NL_DB_READ);
		$nns_org_id = $sp_id;
		$nns_task_type = $c2_info['nns_task_type'];
		$nns_task_id = $c2_info['nns_task_id'];
		$nns_action = $c2_info['nns_action'];

		if(empty($nns_task_id)) return false;
		/*$count = "select count(1) as num from nns_mgtvbk_c2_log where nns_org_id='{$sp_id}' and nns_task_id='{$nns_task_id}' and nns_task_type='{$nns_task_type}'";
		$c = nl_db_get_col($count, $db);
		if($c>=2){
			return true;
		}*/
		
		usleep(5000);
		//if(empty($nns_task_id)) return false;
		$nowtime=date("Y-m-d H:i:s");
		$now_data = date('Y-m-d H:i:s',strtotime("$nowtime-1 hour"));
		$sql = "select 1 from nns_mgtvbk_c2_log where nns_org_id='$nns_org_id' and nns_task_type='$nns_task_type' and nns_task_id='$nns_task_id' and nns_action='$nns_action' and nns_notify_result is null and nns_create_time > NOW() - INTERVAL 3600 SECOND";
		
		//$sql = "select nns_task_id,count(1) as num from nns_mgtvbk_c2_log where nns_create_time > '".$now_data."' and nns_task_type='Movie' group by nns_task_id,nns_action having count(1)> 2;";
		$data = nl_db_get_all($sql,$db_r);
		
		if(is_array($data) && count($data)>0){
			return true;
		}
		return false;
		
		/*
		switch ($nns_task_type) {
			case 'Series':
				$sql = "select * from nns_mgtvbk_c2_task where nns_id='{$nns_task_id}' and nns_org_id='{$nns_org_id}'";
				break;
			case 'Program':
				$sql = "select * from nns_mgtvbk_c2_task where nns_id='{$nns_task_id}' and nns_org_id='{$nns_org_id}'";
				break;
			case 'Movie':
				$sql = "select * from nns_mgtvbk_c2_task where nns_id='{$nns_task_id}' and nns_org_id='{$nns_org_id}'";
				break;
			default:
				return false;
			break;
		}		
		$data = nl_db_get_one($sql,$db_r);
		if(is_array($data)&&$data['nns_status']==5){
			return true;
		}
		return false;*/
	}
	
	
	/**
	 * 保存C2命令日志
	 * $c2_log array(
	 * 'nns_id',
	 * 'nns_type',
	 * 'nns_org_id',
	 * 'nns_video_id',
	 * 'nns_video_type',
	 * 'nns_video_index_id',
	 * 'nns_media_id',
	 * 'nns_url',
	 * 'nns_content',
	 * 'nns_result',
	 * 'nns_desc',
	 * 'nns_create_time'
	 * )
	 */
	static public function save_c2_log($c2_log,$sp_id){
		$db = nn_get_db(NL_DB_WRITE);
		//$db->open();
		$c2_log['nns_type'] = 'std';
		$c2_log['nns_org_id'] = $sp_id;
		$dt = date('Y-m-d H:i:s');
		$c2_log['nns_create_time'] = $dt;
		$c2_log['nns_send_time'] = $dt;
		return nl_db_insert($db,'nns_mgtvbk_c2_log',$c2_log);
	}
	/**
	 * C2通知命令日志
	 * $c2_notify array(
	 * 'nns_id',
	 * 'nns_notify_result_url',
	 * 'nns_notify_result',
	 * 
	 * )
	 */
	static public function save_c2_notify($c2_notify)
	{
		DEBUG && i_write_log_core('---------save_c2_notify----------');
// 		$db = nn_get_db(NL_DB_WRITE);

		
		
		$dc = nl_get_dc(array (
		    "db_policy" => NL_DB_WRITE|NL_DB_READ,
		    "cache_policy" => NP_KV_CACHE_TYPE_MEMCACHE
		));
		$db = $dc->db();
		
		
		$dt = date('Y-m-d H:i:s');
		$wh_content ="";
		if($c2_notify['nns_notify_result']!='-1'){
			$wh_content = "nns_content='',";
		}
		$sql = "update nns_mgtvbk_c2_log set " .
				"nns_notify_result_url='".$c2_notify['nns_notify_result_url']."' ," .$wh_content.
				"nns_notify_result='".$c2_notify['nns_notify_result']."', nns_notify_time='".$dt."'," .
				"nns_modify_time='".$dt."' " .
				"where nns_id='".$c2_notify['nns_id']."'";
		$result_edit= nl_execute_by_db($sql,$db);
// 		echo $sql;die;
		$db_r = nn_get_db(NL_DB_READ);
		$sql = "select * from nns_mgtvbk_c2_log where nns_id='".$c2_notify['nns_id']."'";
		$c2_info = nl_db_get_one($sql,$db_r);
		if($c2_info==false)
        {
            i_write_log_core('---------save_c2_notify----------根据id['.$c2_notify['nns_id'].']查询日志信息失败');
            return false;
        }
		//如果回馈的消息是重发的消息
		if($c2_info['nns_again']>=1){
            i_write_log_core('---------save_c2_notify----------是重发消息');
			return false;
		}
		
		$sp_config = nl_sp::query_by_id($dc, $c2_info['nns_org_id']);
		$sp_config = (isset($sp_config['data_info'][0]['nns_config']) && strlen($sp_config['data_info'][0]['nns_config'])) ? json_decode($sp_config['data_info'][0]['nns_config'],true) : null;
		
		$arr_nns_ex_group = null;
		if($c2_info['nns_task_type']=='Series' || $c2_info['nns_task_type']=='Program'||$c2_info['nns_task_type']=='Movie' || $c2_info['nns_task_type']=='Channel'  || $c2_info['nns_task_type']=='Schedule'||$c2_info['nns_task_type']=='PhysicalChannel'){
			
		    $str_where = " where nns_id='{$c2_info['nns_task_id']}' ";
		    if(isset($c2_info['nns_ex_group']) && strlen($c2_info['nns_ex_group']) >0)
		    {
		        $arr_nns_ex_group = json_decode($c2_info['nns_ex_group'],true);
		        $arr_nns_ex_group = (is_array($arr_nns_ex_group) && !empty($arr_nns_ex_group)) ? $arr_nns_ex_group : null;
		        if(is_array($arr_nns_ex_group) && !empty($arr_nns_ex_group))
		        {
		            $str_where = " where nns_id in('".implode("','", $arr_nns_ex_group)."') ";
		        }
		    }
		    if($c2_notify['nns_notify_result']=='-1'){
				$sql_update = "update nns_mgtvbk_c2_task set nns_status=-1,nns_modify_time=now(),nns_epg_status=97 {$str_where}";//注入媒体时，再次发送；否则媒体注入没有绑定节目			
				/*if($c2_info['nns_action']=='REGIST'){
					$sql_update = "update nns_mgtvbk_c2_task set nns_status=1,nns_action='modify',nns_modify_time=now(),nns_epg_status=97 where nns_id='".$c2_info['nns_task_id']."'";//注入媒体时，再次发送；否则媒体注入没有绑定节目			
				}elseif($c2_info['nns_action']=='UPDATE'){
					$sql_update = "update nns_mgtvbk_c2_task set nns_status=1,nns_action='add',nns_modify_time=now(),nns_epg_status=97 where nns_id='".$c2_info['nns_task_id']."'";//注入媒体时，再次发送；否则媒体注入没有绑定节目
				}*/			
			}else{				
				$sql_update = "update nns_mgtvbk_c2_task set nns_status=0,nns_modify_time=now(),nns_epg_status=97 {$str_where} ";
				
				//是否需要异步获取播放穿
				
				$sp_config = sp_model::get_sp_config($c2_info['nns_org_id']);
				$cdn_query_mediaurl_bool = false;
				if(isset($sp_config['cdn_query_mediaurl'])&&(int)$sp_config['cdn_query_mediaurl']===1){
					$cdn_query_mediaurl_bool = true;
				}				
				if($cdn_query_mediaurl_bool&&$c2_info['nns_task_type']=='Movie'){
					
					$sql_update = "update nns_mgtvbk_c2_task set nns_status=6,nns_modify_time=now(),nns_epg_status=97 {$str_where} ";
					$sql_info = "select * from nns_mgtvbk_c2_task where nns_id='{$c2_info['nns_task_id']}'";
					$c2__taskinfo = nl_db_get_one($sql_info,$db_r);
					
					if(is_array($c2__taskinfo)){
						if($c2__taskinfo['nns_status']=='0'){
							$sql_update = "update nns_mgtvbk_c2_task set nns_status=0,nns_modify_time=now(),nns_epg_status=97 {$str_where} ";
						}
					}
					
					if($c2_info['nns_action']=='DELETE'){
						$sql_update = "update nns_mgtvbk_c2_task set nns_status=0,nns_modify_time=now(),nns_epg_status=97 {$str_where} ";
					}
				}
			}
			$update_re = nl_execute_by_db($sql_update,$db);
            i_write_log_core('更新c2队列状态，sql为' . $sql_update . '结果为' . var_export($update_re, true));
		}
		
		if($c2_info['nns_task_type']=='Movie' && (int)$sp_config['disabled_clip'] !== 2 && (int)$sp_config['disabled_clip'] !== 3){			
			$sql_c2_task = nl_db_get_one("select * from  nns_mgtvbk_c2_task  where nns_id='".$c2_info['nns_task_id']."'", $db);
			if($c2_info['nns_action']=='DELETE'){
				if($c2_notify['nns_notify_result']=='-1'){
					$nns_state = clip_task_model::TASK_C_STATE_C2_DELETE_FAIL;
					$nns_desc = clip_task_model::$task_state_arr[clip_task_model::TASK_C_STATE_C2_DELETE_FAIL];
					//$sql = "update nns_mgtvbk_c2_task set nns_status=-1 where nns_id='".$c2_info['nns_task_id']."'";
					//nl_execute_by_db($sql,$db);		
				}else{
					$nns_state = clip_task_model::TASK_C_STATE_C2_DELETE_SUCC;
					$nns_desc = clip_task_model::$task_state_arr[clip_task_model::TASK_C_STATE_C2_DELETE_SUCC];
					//$sql = "update nns_mgtvbk_c2_task set nns_status=0 where nns_id='".$c2_info['nns_task_id']."'";
					//nl_execute_by_db($sql,$db);		
					
				}
			}else{
				if($c2_notify['nns_notify_result']=='-1'){
					$nns_state = clip_task_model::TASK_C_STATE_C2_FAIL;
					$nns_desc = clip_task_model::$task_state_arr[clip_task_model::TASK_C_STATE_C2_FAIL];
					//$sql = "update nns_mgtvbk_c2_task set nns_status=-1 where nns_id='".$c2_info['nns_task_id']."'";
					//nl_execute_by_db($sql,$db);		
				}else{
					$nns_state = clip_task_model::TASK_C_STATE_C2_SUCC;
					$nns_desc = clip_task_model::$task_state_arr[clip_task_model::TASK_C_STATE_C2_SUCC];
					//$sql = "update nns_mgtvbk_c2_task set nns_status=0 where nns_id='".$c2_info['nns_task_id']."'";
					//if($c2_info['nns_org_id']=='sihua'){
					//	$sql = "update nns_mgtvbk_c2_task set nns_status=6 where nns_id='".$c2_info['nns_task_id']."'";
					//}
					//nl_execute_by_db($sql,$db);
					
				}
			}
			//更改切片状态
			$dt = date('Y-m-d H:i:s');
			$set_state = array(
			'nns_state' => $nns_state,
			'nns_desc' => $nns_desc,
			'nns_modify_time'=>$dt,
			);
			clip_task_model::update_task($sql_c2_task['nns_clip_task_id'], $set_state);
			//任务日志	
			$task_log = array(
			'nns_task_id' => $sql_c2_task['nns_clip_task_id'],
			'nns_state' => $nns_state,
			'nns_desc' => $nns_desc,
			);	
			clip_task_model::add_task_log($task_log);
		}
		if($c2_info['nns_task_type']=='Movie' && $c2_notify['nns_notify_result']!='-1' && ($c2_info['nns_org_id']=='cqyx' ||$c2_info['nns_org_id']=='cqyx_hw'))
		{
				$sql_by_query_index_import_id = "SELECT nns_import_id FROM nns_vod_index WHERE nns_id=(SELECT nns_src_id FROM nns_mgtvbk_c2_task WHERE nns_id='".$c2_info['nns_task_id']."')";
				$query_result = nl_query_by_db($sql_by_query_index_import_id,$db);
				$index_import_id = $query_result[0]['nns_import_id'];
				$sql = "update nns_mgtvbk_c2_task set nns_status=0,nns_ex_url='".$index_import_id."' where nns_id='".$c2_info['nns_task_id']."'";
				nl_execute_by_db($sql,$db);
		}
		
		if(isset($c2_notify['nns_notify_PlayId']) && strlen($c2_notify['nns_notify_PlayId']) >0)
		{
		    $sql_by_query_index_import_id = "select * from nns_vod_media WHERE nns_id=(SELECT nns_ref_id FROM nns_mgtvbk_c2_task WHERE nns_id='".$c2_info['nns_task_id']."') limit 1";
// echo $sql_by_query_index_import_id;die;
			$query_result = nl_query_by_db($sql_by_query_index_import_id,$db);
			$query_result  = isset($query_result[0]) ? $query_result[0] :null;
			if(is_array($query_result))
			{
			    $sql_update_media ="update nns_vod_media set nns_content_id='{$c2_notify['nns_notify_PlayId']}',nns_media_service='{$sp_config['media_service_type']}' where nns_id='{$query_result['nns_id']}'";
			    nl_execute_by_db($sql_update_media,$db);
			    $query_result['nns_content_id'] = $c2_notify['nns_notify_PlayId'];
// 			    if(strlen($sp_config['media_service_type']) >0 && strrpos($query_result['nns_import_id'], '_'.$sp_config['media_service_type']))
// 			    {
			        $query_result['nns_import_id'] = substr($query_result['nns_import_id'],0,(strlen($query_result['nns_import_id'])-strlen($sp_config['media_service_type'])-1));
// 			    }
			    $result_c2_task_info = nl_query_by_db("select * from nns_mgtvbk_c2_task where nns_id='{$c2_info['nns_task_id']}'",$db);
			    $result_c2_task_info = $result_c2_task_info[0];
			    
			    
			    $result_1 = self::notify_upstream($query_result,$c2_info['nns_action'],array('ret'=>0),$sp_config,$result_c2_task_info,$dc);
			    nn_log::write_log_message(LOG_MODEL_BK_CDN_NOTIFY,"消息反馈上游结果".var_export($result_1,true), ORG_ID);
			}
		}

		//通知列队
		if($c2_notify['nns_notify_result']!='-1')
		{
		    self::notify_org_platfrom($dc,$c2_notify,$sp_config,$c2_info);
			include_once 'queue_task_model.php';
			if(!empty($arr_nns_ex_group) && is_array($arr_nns_ex_group))
			{
			    foreach ($arr_nns_ex_group as $group_id)
			    {
			        $queue_task_model = new queue_task_model();
			        $queue_task_model->q_report_task($group_id);
			        unset($queue_task_model);
			        $queue_task_model=null;
			    }
			}
			else
			{
    			$queue_task_model = new queue_task_model();
    			$queue_task_model->q_report_task($c2_info['nns_task_id']);
    			unset($queue_task_model);
    			$queue_task_model=null;
			}
			if(isset($sp_config['cdn_notify_third_party_enable']) && $sp_config['cdn_notify_third_party_enable'] =='1' && isset($sp_config['cdn_notify_third_party_mark']) && strlen($sp_config['cdn_notify_third_party_mark'])>0)
			{
			     $result_1 = self::notify_upstream_third($c2_info['nns_task_id'],$sp_config,$dc,$c2_notify['nns_id']);
 			     i_write_log_core('消息反馈上游结果:'.var_export($result_1,true),ORG_ID.'/c2notify');
			}
		}
        else
        {  
            if(!empty($arr_nns_ex_group) && is_array($arr_nns_ex_group))
            {
                $c2_task_info['nns_cdn_fail_time'] = $c2_task_info['nns_cdn_fail_time']+1;
                $str_temp_set = ($sp_config['cdn_fail_retry_mode'] == '0' && $c2_task_info['nns_cdn_fail_time'] <= $sp_config['cdn_fail_retry_time']) ? ",nns_status='1'" : '';
                $time = date("Y-m-d H:i:s");
                $sql_c2 = "update nns_mgtvbk_c2_task set nns_cdn_fail_time=nns_cdn_fail_time+1,nns_modify_time='{$time}'{$str_temp_set} where nns_id in('".implode("','", $arr_nns_ex_group)."')";
                nl_execute_by_db($sql_c2,$db);
            }
            else
            {
                //注入cdn反馈失败之后，添加失败次数，然后将c2队列的状态置为等待注入
                $sql_info = "select * from nns_mgtvbk_c2_task where nns_id='{$c2_info['nns_task_id']}'";
                $c2_task_info = nl_db_get_one($sql_info,$db_r);
                //添加失败次数
                $c2_task_info['nns_cdn_fail_time'] = $c2_task_info['nns_cdn_fail_time']+1;
                $sql_c2 = "update nns_mgtvbk_c2_task set nns_cdn_fail_time=".$c2_task_info['nns_cdn_fail_time']." where nns_id='".$c2_info['nns_task_id']."'";
                nl_execute_by_db($sql_c2,$db);
                if($sp_config['cdn_fail_retry_mode'] == '0' && $c2_task_info['nns_cdn_fail_time'] <= $sp_config['cdn_fail_retry_time'])
                {
                    $sql_c2 = "update nns_mgtvbk_c2_task set nns_status='1' where nns_id='".$c2_info['nns_task_id']."'";
                    $result = nl_execute_by_db($sql_c2,$db);
                    if(!$result)
                    {
                        DEBUG && i_write_log_core('---------注入失败后未到失败，重置C2状态失败----------',$c2_info['nns_org_id'].'/c2notify');
                    }
                }
            }
        }
		//下载结果
		if(!empty($c2_notify['nns_notify_result_url']))
		{
            $result = self::handle_notify_result_url($dc,$sp_config,$c2_info,$c2_notify);
            if(isset($result['data_info']['base_path']) && strlen($result['data_info']['base_path']) >0)
            {
                $sql = "update nns_mgtvbk_c2_log set nns_notify_content='{$result['data_info']['base_path']}' where nns_id='{$c2_notify['nns_id']}'";
                nl_execute_by_db($sql,$db);
            }
		    
		}
		else if(isset($c2_notify['nns_notify_content']) && strlen($c2_notify['nns_notify_content']) >0)
		{
		    $result = self::make_notify_dir($c2_info);
		    if(isset($result['data_info']['full_path']) && strlen($result['data_info']['full_path']) >0)
		    {
		        file_put_contents($result['data_info']['full_path'], $c2_notify['nns_notify_content']);
    		    $sql = "update nns_mgtvbk_c2_log set nns_notify_content='{$result['data_info']['base_path']}' where nns_id='{$c2_notify['nns_id']}'";
    		    nl_execute_by_db($sql,$db);
		    }
		}
		return true;
	}

	/**
	 * 消息反馈上游
	 * @param unknown $dc
	 * @param unknown $c2_notify
	 * @param unknown $sp_config
	 * @param string $c2_info
	 */
	static public function notify_org_platfrom($dc,$c2_notify,$sp_config,$c2_info=null)
	{
	    if(empty($c2_info) || !is_array($c2_info) || !isset($c2_info))
	    {
	        if(!isset($c2_notify['nns_task_id']) || strlen($c2_notify['nns_task_id']) <1)
	        {
	            return false;
	        }
	        $sql_c2_info = "select * from nns_mgtvbk_c2_task WHERE nns_id='{$c2_notify['nns_task_id']}' limit 1";
	        $c2_info = nl_query_by_db($sql_c2_info,$dc->db());
	        $c2_info  = isset($c2_info[0]) ? $c2_info[0] :null;
	    }
	    if(empty($c2_info) || !is_array($c2_info))
	    {
	        return false;
	    }
	    if((isset($c2_notify['nns_notify_PlayId']) && strlen($c2_notify['nns_notify_PlayId']) >0) || ($c2_info['nns_org_id'] != 'cbczq_zte' && $c2_info['nns_org_id'] != 'xjdx_zte') || !in_array($c2_info['nns_task_type'],array('Movie','Series','Program')))
	    {
	        return true;
	    }
        switch ($c2_info['nns_task_type'])
        {
            case 'Movie':
                $sql_by_query_index_import_id = "select * from nns_vod_media WHERE nns_id=(SELECT nns_ref_id FROM nns_mgtvbk_c2_task WHERE nns_id='{$c2_info['nns_task_id']}') limit 1";
                break;
            case 'Series':
                $sql_by_query_index_import_id = "select * from nns_vod WHERE nns_id=(SELECT nns_ref_id FROM nns_mgtvbk_c2_task WHERE nns_id='{$c2_info['nns_task_id']}') limit 1";
                break;
            case 'Program':
                $sql_by_query_index_import_id = "select * from nns_vod_index WHERE nns_id=(SELECT nns_ref_id FROM nns_mgtvbk_c2_task WHERE nns_id='{$c2_info['nns_task_id']}') limit 1";
                break;
            default:
                return false;
        }
        $query_result = nl_query_by_db($sql_by_query_index_import_id,$dc->db());
        $query_result  = isset($query_result[0]) ? $query_result[0] :null;
        if(empty($query_result) || !is_array($query_result))
        {
            return false;
        }
        if($c2_info['nns_task_type'] == 'Series')
        {
            $query_result['nns_import_id'] = $query_result['nns_asset_import_id'];
        }
        if(strlen($query_result['nns_cp_id']) >5 && substr($query_result['nns_cp_id'], 0,5) == 'fuse_')
        {
            $temp_nns_import_id =  substr($query_result['nns_cp_id'], 5);
            switch ($c2_info['nns_task_type'])
            {
                case 'Movie':
                    $sql_c2_task_info = "select * from nns_mgtvbk_c2_task where nns_ref_id=(select nns_id from nns_vod_media WHERE nns_import_id='{$query_result['nns_import_id']}' and nns_cp_id='{$temp_nns_import_id}' limit 1) and nns_org_id='starcor_make' limit 1";
                    break;
                case 'Series':
                    $sql_c2_task_info = "select * from nns_mgtvbk_c2_task where nns_ref_id=(select nns_id from nns_vod WHERE nns_asset_import_id='{$query_result['nns_asset_import_id']}' and nns_cp_id='{$temp_nns_import_id}' limit 1) and nns_org_id='starcor_make' limit 1";
                    break;
                case 'Program':
                    $sql_c2_task_info = "select * from nns_mgtvbk_c2_task where nns_ref_id=(select nns_id from nns_vod_index WHERE nns_import_id='{$query_result['nns_import_id']}' and nns_cp_id='{$temp_nns_import_id}' limit 1) and nns_org_id='starcor_make' limit 1";
                    break;
                default:
                    return false;
            }
            if($c2_info['nns_task_type'] == 'Movie')
            {
                $sql_org_media="select * from nns_vod_media WHERE nns_import_id='{$query_result['nns_import_id']}' and nns_cp_id='{$temp_nns_import_id}' limit 1";
                $result_org_media = nl_query_by_db($sql_org_media,$dc->db());
                if(!isset($result_org_media[0]) || empty($result_org_media[0]) || !is_array($result_org_media[0]))
                {
                    return false;
                }
                if($result_org_media[0]['nns_encode_flag'] == '1')
                {
                    $sql_org_file_encode = "SELECT nns_in_media_id FROM `nns_file_encode` where nns_sp_id='starcor_make' and nns_cp_id='{$temp_nns_import_id}' and nns_out_media_id='{$result_org_media[0]['nns_id']}'";
                    $result_org_file_encode = nl_query_by_db($sql_org_file_encode,$dc->db());
                    if(isset($result_org_file_encode[0]) && !empty($result_org_file_encode[0]) && is_array($result_org_file_encode[0]))
                    {
                        $sql_org_media="select * from nns_vod_media where nns_id ='{$result_org_file_encode[0]['nns_in_media_id']}' limit 1";
                        $result_org_media = nl_query_by_db($sql_org_media,$dc->db());
                        if(isset($result_org_media[0]) && !empty($result_org_media[0]) && is_array($result_org_media[0]))
                        {
                            $result_org_media[0]['nns_cp_id'] = $query_result['nns_cp_id'];
                            $query_result = $result_org_media[0];
                        }
                    }
                }
                else
                {
                    $result_org_media[0]['nns_cp_id'] = $query_result['nns_cp_id'];
                    $query_result = $result_org_media[0];
                }
            }
            
            $result_c2_task_info = nl_query_by_db($sql_c2_task_info,$dc->db());
            $result_c2_task_info  = isset($result_c2_task_info[0]) ? $result_c2_task_info[0] :null;
            if(empty($result_c2_task_info) || !is_array($result_c2_task_info))
            {
                return false;
            }
            $result_asset_id_by_sp_id = public_model_exec::get_asset_id_by_sp_id($c2_info['nns_org_id'], 'media', $query_result['nns_id'],$query_result,$sp_config,'cdn');
            if($result_asset_id_by_sp_id['ret'] !=0 || !isset($result_asset_id_by_sp_id['data_info']) || strlen($result_asset_id_by_sp_id['data_info']) <1)
            {
                nn_log::write_log_message(LOG_MODEL_BK_CDN_NOTIFY,"消息反馈上游播放串查询注入CDN的播放ID，结果有误".var_export($result_asset_id_by_sp_id,true), ORG_ID);
                return false;
            }
            $query_result['nns_content_id'] = $result_asset_id_by_sp_id['data_info'];
            $result_1 = self::notify_upstream($query_result,$c2_info['nns_action'],array('ret'=>0),$sp_config,$result_c2_task_info,$dc,$result_c2_task_info['nns_type'],$c2_info['nns_org_id']);
            nn_log::write_log_message(LOG_MODEL_BK_CDN_NOTIFY,"消息反馈上游结果".var_export($result_1,true), ORG_ID);
        }
        else
        {
            $sql_c2_task = "select * from nns_mgtvbk_c2_task where nns_id='{$c2_info['nns_task_id']}'";
            $result_c2_task_info = nl_query_by_db($sql_c2_task,$dc->db());
            $result_c2_task_info = (isset($result_c2_task_info[0]) && is_array($result_c2_task_info[0]) && !empty($result_c2_task_info[0])) ? $result_c2_task_info[0] : null;
            if(empty($result_c2_task_info) || !is_array($result_c2_task_info))
            {
                return false;
            }
            $result_asset_id_by_sp_id = public_model_exec::get_asset_id_by_sp_id($c2_info['nns_org_id'], $result_c2_task_info['nns_type'], $query_result['nns_id'],$query_result,$sp_config,'cdn');
            if($result_asset_id_by_sp_id['ret'] !=0 || !isset($result_asset_id_by_sp_id['data_info']) || strlen($result_asset_id_by_sp_id['data_info']) <1)
            {
                nn_log::write_log_message(LOG_MODEL_BK_CDN_NOTIFY,"消息反馈上游播放串查询注入CDN的播放ID，结果有误".var_export($result_asset_id_by_sp_id,true), ORG_ID);
                return false;
            }
            $query_result['nns_content_id'] = $result_asset_id_by_sp_id['data_info'];
            $result_1 = self::notify_upstream($query_result,$c2_info['nns_action'],array('ret'=>0),$sp_config,$result_c2_task_info,$dc,$result_c2_task_info['nns_type'],$c2_info['nns_org_id']);
            nn_log::write_log_message(LOG_MODEL_BK_CDN_NOTIFY,"消息反馈上游结果".var_export($result_1,true), ORG_ID);
        }
        return true;
	}
	
	static public function save_c2_notify_v2($c2_notify)
	{
	    if(!defined(ORG_ID))
	    {
	        define('ORG_ID', 'public');
	    }
	
	    $bk_state_flag = true;
	    $c2_ext_info = $c2_task_log = null;
	    if(isset($c2_notify['nns_error_description']))
	    {
	        if(strlen($c2_notify['nns_error_description']) >0)
	        {
	            $c2_ext_info['CDN_notify'] =$c2_notify['nns_error_description'];
	        }
	        unset($c2_notify['nns_error_description']);
	    }
	    $dc = nl_get_dc(array (
	        "db_policy" => NL_DB_READ|NL_DB_WRITE,
	        "cache_policy" => NP_KV_CACHE_TYPE_MEMCACHE
	    ));
	    $str_date_file = date('Ymd');
	    $dt = date('Y-m-d H:i:s');
	    //查询 c2 日志
	    $sql = "select * from nns_mgtvbk_c2_log where nns_id='".$c2_notify['nns_id']."'";
	    $c2_info = nl_db_get_one($sql,$dc->db());
	    if(!is_array($c2_info) || empty($c2_info))
	    {
	        nn_log::write_log_message(LOG_MODEL_BK_CDN_NOTIFY, "查询c2_log表数据不存在SQL:{$sql}", ORG_ID);
	        return self::return_desc(1,'queue log is lost');
	    }
	    //如果回馈的消息是重发的消息
	    if($c2_info['nns_again']>=1)
	    {
	        nn_log::write_log_message(LOG_MODEL_BK_CDN_NOTIFY, "消息发送了一次不允许再次接收该消息", ORG_ID);
	        return self::return_desc(1,'queue send twice again');
	    }
	
	    //查询 c2_task 队列
	    $sql_c2 = "select * from  nns_mgtvbk_c2_task  where nns_id='{$c2_info['nns_task_id']}'";
	    $sql_c2_task = nl_db_get_one($sql_c2, $dc->db());
	    if(!is_array($sql_c2_task) || empty($sql_c2_task))
	    {
	        nn_log::write_log_message(LOG_MODEL_BK_CDN_NOTIFY, "查询c2_task表数据不存在SQL:{$sql_c2}", ORG_ID);
	        return self::return_desc(1,'queue is lost');
	    }
	
	    $sp_config = nl_sp::query_by_id($dc, $c2_info['nns_org_id']);
	    $sp_config = (isset($sp_config['data_info'][0]['nns_config']) && strlen($sp_config['data_info'][0]['nns_config'])) ? json_decode($sp_config['data_info'][0]['nns_config'],true) : null;
	
	
	    //下载结果  消息日志记录
	    if(!empty($c2_notify['nns_notify_result_url']))
	    {
	        $result = self::handle_notify_result_url($dc,$sp_config,$c2_info,$c2_notify);
	        if($result['ret'] !=0)
	        {
	            $bk_state_flag = false;
	            $c2_ext_info[] = $result['reason'];
	        }
	        $c2_task_log['nns_notify_content'] = isset($result['data_info']['base_path']) ? $result['data_info']['base_path'] : '';
	    }
	    else if(isset($c2_notify['nns_notify_content']) && strlen($c2_notify['nns_notify_content']) >0)
	    {
	        $result = self::make_notify_dir($c2_info);
	        if($result['ret'] !=0)
	        {
	            $bk_state_flag = false;
	            $c2_ext_info[] = $result['reason'];
	        }
	        if(isset($result['data_info']['full_path']) && strlen($result['data_info']['full_path']) >0)
	        {
	            $put_file = file_put_contents($result['data_info']['full_path'], $c2_notify['nns_notify_content']);
	            if(!$put_file)
	            {
	                $bk_state_flag = false;
	                $c2_ext_info[] = 'content file fut error';
	            }
	            $c2_task_log['nns_notify_content'] = $result['data_info']['base_path'];
	        }
	    }
	    //切片队列处理
	    if($c2_info['nns_task_type']=='Movie' && (int)$sp_config['disabled_clip'] !== 2 && (int)$sp_config['disabled_clip'] !== 3)
	    {
	        if($c2_info['nns_action']=='DELETE')
	        {
	            if($c2_notify['nns_notify_result']=='-1')
	            {
	                $nns_state = clip_task_model::TASK_C_STATE_C2_DELETE_FAIL;
	                $nns_desc = clip_task_model::$task_state_arr[clip_task_model::TASK_C_STATE_C2_DELETE_FAIL];
	            }
	            else
	            {
	                $nns_state = clip_task_model::TASK_C_STATE_C2_DELETE_SUCC;
	                $nns_desc = clip_task_model::$task_state_arr[clip_task_model::TASK_C_STATE_C2_DELETE_SUCC];
	            }
	        }
	        else
	        {
	            if($c2_notify['nns_notify_result']=='-1')
	            {
	                $nns_state = clip_task_model::TASK_C_STATE_C2_FAIL;
	                $nns_desc = clip_task_model::$task_state_arr[clip_task_model::TASK_C_STATE_C2_FAIL];
	            }
	            else
	            {
	                $nns_state = clip_task_model::TASK_C_STATE_C2_SUCC;
	                $nns_desc = clip_task_model::$task_state_arr[clip_task_model::TASK_C_STATE_C2_SUCC];
	            }
	        }
	        //更改切片状态
	        $set_state = array(
	            'nns_state' => $nns_state,
	            'nns_desc' => $nns_desc,
	            'nns_modify_time'=>$dt,
	        );
	        clip_task_model::update_task($sql_c2_task['nns_clip_task_id'], $set_state);
	        //任务日志
	        $task_log = array(
	            'nns_task_id' => $sql_c2_task['nns_clip_task_id'],
	            'nns_state' => $nns_state,
	            'nns_desc' => $nns_desc,
	        );
	        clip_task_model::add_task_log($task_log);
	    }
	    $result_notify = self::notify_cp_info($c2_info, $sp_config, $dc, $c2_notify,$sql_c2_task);
	    if($result_notify['ret'] !=0)
	    {
	        $bk_state_flag = false;
	        $c2_ext_info[] = $result_notify['reason'];
	    }
	
	    if($c2_notify['nns_notify_result']!='-1')
	    {
	        $c2_task_log['nns_content'] = '';
	    }
	    $c2_task_log['nns_notify_result_url'] = $c2_notify['nns_notify_result_url'];
	    $c2_task_log['nns_notify_result'] = $c2_notify['nns_notify_result'];
	    $c2_task_log['nns_modify_time'] = $c2_task_log['nns_notify_time'] = $dt;
	    if(is_array($c2_ext_info) && !empty($c2_ext_info))
	    {
	        $c2_task_log['nns_desc'] = json_encode($c2_ext_info);
	    }
	
	    $sql = "update nns_mgtvbk_c2_log set ";
	    foreach ($c2_task_log as $c2_log_key => $c2_log_val)
	    {
	        $sql.=" {$c2_log_key}='{$c2_log_val}',";
	    }
	    $sql = rtrim($sql,',');
	    $sql.=" where nns_id='{$c2_notify['nns_id']}'";
	    $result_ex_c2_log = nl_execute_by_db($sql,$dc->db());
	    if(!$result_ex_c2_log)
	    {
	        nn_log::write_log_message(LOG_MODEL_BK_CDN_NOTIFY, "执行c2_log表数据库执行失败SQL:{$sql}", ORG_ID);
	    }
	    if($c2_notify['nns_notify_result']=='-1' || !$bk_state_flag)
	    {
	        if($sp_config['cdn_fail_retry_mode'] == '0' && $c2_info['nns_cdn_fail_time'] <= $sp_config['cdn_fail_retry_time'])
	        {
	            $sql_update = "update nns_mgtvbk_c2_task set nns_status=1,nns_modify_time='{$dt}',nns_epg_status=97,nns_cdn_fail_time=nns_cdn_fail_time+1 where nns_id='{$c2_info['nns_task_id']}'";
	        }
	        else
	        {
	            $sql_update = "update nns_mgtvbk_c2_task set nns_status=-1,nns_modify_time='{$dt}',nns_epg_status=97 where nns_id='{$c2_info['nns_task_id']}'";
	        }
	        nl_execute_by_db($sql_update,$dc->db());
	    }
	    else
	    {
	        //是否需要异步获取播放穿
	        if(isset($sp_config['cdn_query_mediaurl'])&&(int)$sp_config['cdn_query_mediaurl']===1 && $c2_info['nns_task_type']=='Movie')
	        {
	            $str_state = "nns_status=6,";
	            if(isset($sp_config['cdn_send_cdi_mode_url']) && strlen($sp_config['cdn_send_cdi_mode_url']) >0)
	            {
	                $str_state = "nns_status=12,";
	            }
	            $sql_update = "update nns_mgtvbk_c2_task set {$str_state}nns_modify_time='{$dt}',nns_epg_status=97 where nns_id='{$c2_info['nns_task_id']}'";
	            nl_execute_by_db($sql_update,$dc->db());
	        }
	        else
	        {
	            if($c2_info['nns_task_type']=='Movie' && ($c2_info['nns_org_id']=='cqyx' ||$c2_info['nns_org_id']=='cqyx_hw'))
	            {
	                $sql_by_query_index_import_id = "SELECT nns_import_id FROM nns_vod_index WHERE nns_id=(SELECT nns_src_id FROM nns_mgtvbk_c2_task WHERE nns_id='".$c2_info['nns_task_id']."')";
	                $query_result = nl_query_by_db($sql_by_query_index_import_id,$dc->db());
	                $index_import_id = $query_result[0]['nns_import_id'];
	                $sql_update = "update nns_mgtvbk_c2_task set nns_status=0,nns_ex_url='{$index_import_id}',nns_modify_time='{$dt}' where nns_id='".$c2_info['nns_task_id']."'";
	                nl_execute_by_db($sql_update,$dc->db());
	            }
	            else
	            {
	                $sql_update = "update nns_mgtvbk_c2_task set nns_status=0,nns_modify_time='{$dt}',nns_epg_status=97 where nns_id='{$c2_info['nns_task_id']}'";
	                nl_execute_by_db($sql_update,$dc->db());
	            }
	        }
	    }
	    if($bk_state_flag == true)
	    {
	        include_once 'queue_task_model.php';
	        $queue_task_model = new queue_task_model();
	        $queue_task_model->q_report_task($c2_info['nns_task_id']);
	        unset($queue_task_model);
	    }
	    return self::return_desc(0,'ok');
	}
	
	
	
	static public function save_c2_notify_v3($c2_notify)
	{
	    if(!defined(ORG_ID))
	    {
	        define('ORG_ID', 'public');
	    }
	    $bk_state_flag = true;
	    $c2_ext_info = $c2_task_log = null;
	    if(isset($c2_notify['nns_error_description']))
	    {
	        if(strlen($c2_notify['nns_error_description']) >0)
	        {
	            $c2_ext_info['CDN_notify'] =$c2_notify['nns_error_description'];
	        }
	        unset($c2_notify['nns_error_description']);
	    }
	    $dc = nl_get_dc(array (
	        "db_policy" => NL_DB_READ|NL_DB_WRITE,
	        "cache_policy" => NP_KV_CACHE_TYPE_MEMCACHE
	    ));
	    $str_date_file = date('Ymd');
	    $dt = date('Y-m-d H:i:s');
	    //查询 c2 日志
	    $sql = "select * from nns_mgtvbk_c2_log where nns_id='".$c2_notify['nns_id']."'";
	    $c2_info = nl_db_get_one($sql,$dc->db());
	    $c2_task_log = $c2_info;
	    $c2_task_log['nns_id'] = np_guid_rand();
	    if(!is_array($c2_info) || empty($c2_info))
	    {
	        nn_log::write_log_message(LOG_MODEL_BK_CDN_NOTIFY, "查询c2_log表数据不存在SQL:{$sql}", ORG_ID);
	        return self::return_desc(1,'queue log is lost');
	    }
	    //如果回馈的消息是重发的消息
	    if($c2_info['nns_again']>=1)
	    {
	        nn_log::write_log_message(LOG_MODEL_BK_CDN_NOTIFY, "消息发送了一次不允许再次接收该消息", ORG_ID);
	        return self::return_desc(1,'queue send twice again');
	    }
	
	    //查询 c2_task 队列
	    $sql_c2 = "select * from  nns_mgtvbk_c2_task  where nns_id='{$c2_info['nns_task_id']}'";
	    $sql_c2_task = nl_db_get_one($sql_c2, $dc->db());
	    if(!is_array($sql_c2_task) || empty($sql_c2_task))
	    {
	        nn_log::write_log_message(LOG_MODEL_BK_CDN_NOTIFY, "查询c2_task表数据不存在SQL:{$sql_c2}", ORG_ID);
	        return self::return_desc(1,'queue is lost');
	    }
	    $sp_config = nl_sp::query_by_id($dc, $c2_info['nns_org_id']);
	    $sp_config = (isset($sp_config['data_info'][0]['nns_config']) && strlen($sp_config['data_info'][0]['nns_config'])) ? json_decode($sp_config['data_info'][0]['nns_config'],true) : null;
	
	
	    //下载结果  消息日志记录
	    if(!empty($c2_notify['nns_notify_result_url']))
	    {
	        $result = self::handle_notify_result_url($dc,$sp_config,$c2_info,$c2_notify);
	        if($result['ret'] !=0)
	        {
	            $bk_state_flag = false;
	            $c2_ext_info[] = $result['reason'];
	        }
	        $c2_task_log['nns_notify_content'] = isset($result['data_info']['base_path']) ? $result['data_info']['base_path'] : '';
	    }
	    else if(isset($c2_notify['nns_notify_content']) && strlen($c2_notify['nns_notify_content']) >0)
	    {
	        $result = self::make_notify_dir($c2_info);
	        if($result['ret'] !=0)
	        {
	            $bk_state_flag = false;
	            $c2_ext_info[] = $result['reason'];
	        }
	        if(isset($result['data_info']['full_path']) && strlen($result['data_info']['full_path']) >0)
	        {
	            $put_file = file_put_contents($result['data_info']['full_path'], $c2_notify['nns_notify_content']);
	            if(!$put_file)
	            {
	                $bk_state_flag = false;
	                $c2_ext_info[] = 'content file fut error';
	            }
	            $c2_task_log['nns_notify_content'] = $result['data_info']['base_path'];
	        }
	    }
	    //切片队列处理
	    if($c2_info['nns_task_type']=='Movie' && (int)$sp_config['disabled_clip'] !== 2 && (int)$sp_config['disabled_clip'] !== 3)
	    {
	        if($c2_info['nns_action']=='DELETE')
	        {
	            if($c2_notify['nns_notify_result']=='-1')
	            {
	                $nns_state = clip_task_model::TASK_C_STATE_C2_DELETE_FAIL;
	                $nns_desc = clip_task_model::$task_state_arr[clip_task_model::TASK_C_STATE_C2_DELETE_FAIL];
	            }
	            else
	            {
	                $nns_state = clip_task_model::TASK_C_STATE_C2_DELETE_SUCC;
	                $nns_desc = clip_task_model::$task_state_arr[clip_task_model::TASK_C_STATE_C2_DELETE_SUCC];
	            }
	        }
	        else
	        {
	            if($c2_notify['nns_notify_result']=='-1')
	            {
	                $nns_state = clip_task_model::TASK_C_STATE_C2_FAIL;
	                $nns_desc = clip_task_model::$task_state_arr[clip_task_model::TASK_C_STATE_C2_FAIL];
	            }
	            else
	            {
	                $nns_state = clip_task_model::TASK_C_STATE_C2_SUCC;
	                $nns_desc = clip_task_model::$task_state_arr[clip_task_model::TASK_C_STATE_C2_SUCC];
	            }
	        }
	        //更改切片状态
	        $set_state = array(
	            'nns_state' => $nns_state,
	            'nns_desc' => $nns_desc,
	            'nns_modify_time'=>$dt,
	        );
	        clip_task_model::update_task($sql_c2_task['nns_clip_task_id'], $set_state);
	        //任务日志
	        $task_log = array(
	            'nns_task_id' => $sql_c2_task['nns_clip_task_id'],
	            'nns_state' => $nns_state,
	            'nns_desc' => $nns_desc,
	        );
	        clip_task_model::add_task_log($task_log);
	    }
	    $result_notify = self::notify_cp_info($c2_info, $sp_config, $dc, $c2_notify,$sql_c2_task);
	    if($result_notify['ret'] !=0)
	    {
	        $bk_state_flag = false;
	        $c2_ext_info[] = $result_notify['reason'];
	    }
	
	    if($c2_notify['nns_notify_result']!='-1')
	    {
	        $c2_task_log['nns_content'] = '';
	    }
	    $c2_task_log['nns_notify_result_url'] = $c2_notify['nns_notify_result_url'];
	    $c2_task_log['nns_notify_result'] = $c2_notify['nns_notify_result'];
	    $c2_task_log['nns_modify_time'] = $c2_task_log['nns_notify_time'] = $dt;
	    if(is_array($c2_ext_info) && !empty($c2_ext_info))
	    {
	        $c2_task_log['nns_desc'] = json_encode($c2_ext_info);
	    }
	
	    $sql = "insert into nns_mgtvbk_c2_log ";
	    $str_sql_filed = '';
	    $str_sql_val = '';
	    foreach ($c2_task_log as $c2_log_key => $c2_log_val)
	    {
	        $str_sql_filed.="{$c2_log_key},";
	        $str_sql_val.="'{$c2_log_val}',";
	    }
	    $str_sql_filed = rtrim($str_sql_filed,',');
	    $str_sql_val = rtrim($str_sql_val,',');
	    $sql = "insert into nns_mgtvbk_c2_log ({$str_sql_filed}) values({$str_sql_val})";
	    $result_ex_c2_log = nl_execute_by_db($sql,$dc->db());
	    if(!$result_ex_c2_log)
	    {
	        nn_log::write_log_message(LOG_MODEL_BK_CDN_NOTIFY, "执行c2_log表数据库执行失败SQL:{$sql}", ORG_ID);
	    }
	    if($c2_notify['nns_notify_result']=='-1' || !$bk_state_flag)
	    {
	        if($sp_config['cdn_fail_retry_mode'] == '0' && $c2_info['nns_cdn_fail_time'] <= $sp_config['cdn_fail_retry_time'])
	        {
	            $sql_update = "update nns_mgtvbk_c2_task set nns_status=1,nns_modify_time='{$dt}',nns_epg_status=97,nns_cdn_fail_time=nns_cdn_fail_time+1 where nns_id='{$c2_info['nns_task_id']}'";
	        }
	        else
	        {
	            $sql_update = "update nns_mgtvbk_c2_task set nns_status=-1,nns_modify_time='{$dt}',nns_epg_status=97 where nns_id='{$c2_info['nns_task_id']}'";
	        }
	        nl_execute_by_db($sql_update,$dc->db());
	    }
	    else
	    {
            if($c2_info['nns_task_type']=='Movie' && ($c2_info['nns_org_id']=='cqyx' ||$c2_info['nns_org_id']=='cqyx_hw'))
            {
                $sql_by_query_index_import_id = "SELECT nns_import_id FROM nns_vod_index WHERE nns_id=(SELECT nns_src_id FROM nns_mgtvbk_c2_task WHERE nns_id='".$c2_info['nns_task_id']."')";
                $query_result = nl_query_by_db($sql_by_query_index_import_id,$dc->db());
                $index_import_id = $query_result[0]['nns_import_id'];
                $sql_update = "update nns_mgtvbk_c2_task set nns_status=0,nns_ex_url='".$index_import_id."' where nns_id='".$c2_info['nns_task_id']."'";
                nl_execute_by_db($sql_update,$dc->db());
            }
            else
            {
	            $sql_update = "update nns_mgtvbk_c2_task set nns_status=0,nns_modify_time='{$dt}',nns_epg_status=97 where nns_id='{$c2_info['nns_task_id']}'";
	            nl_execute_by_db($sql_update,$dc->db());
            }
	    }
	    if($bk_state_flag == true)
	    {
	        include_once 'queue_task_model.php';
	        $queue_task_model = new queue_task_model();
	        $queue_task_model->q_report_task($c2_info['nns_task_id']);
	        unset($queue_task_model);
	    }
	    return self::return_desc(0,'ok');
	}
	
	
	/**
	 * 消息反馈公共方法
	 * @param unknown $c2_info
	 * @param unknown $sp_config
	 * @param unknown $dc
	 * @param unknown $c2_notify
	 * @return Ambigous <multitype:number , multitype:unknown string >
	 */
	static public function notify_cp_info($c2_info,$sp_config,$dc,$c2_notify,$sql_c2_task)
	{
	    if(isset($sp_config['cdn_notify_third_party_enable']) && $sp_config['cdn_notify_third_party_enable'] =='1' && isset($sp_config['cdn_notify_third_party_mark']) && strlen($sp_config['cdn_notify_third_party_mark'])>0)
	    {
	        $result = self::notify_upstream_third($c2_info['nns_task_id'],$sp_config,$dc,$c2_notify['nns_id']);
	    }
	    else if(isset($sp_config['cdn_notify_third_party_enable']) && $sp_config['cdn_notify_third_party_enable'] =='1' && isset($c2_notify['nns_notify_PlayId']))
	    {
	        if(strlen($c2_notify['nns_notify_PlayId']) <1)
	        {
	            $result = self::return_desc('1',"下游CDN反馈的播放ID为空下游CDN有问题为空");
	            nn_log::write_log_message(LOG_MODEL_BK_CDN_NOTIFY,"消息反馈上游播放串结果".var_export($result,true), ORG_ID);
	            return $result;
	        }
	        $sql_by_query_index_import_id = "select * from nns_vod_media WHERE nns_id=(SELECT nns_ref_id FROM nns_mgtvbk_c2_task WHERE nns_id='{$c2_info['nns_task_id']}') limit 1";
	        $query_result = nl_query_by_db($sql_by_query_index_import_id,$dc->db());
	        $query_result  = isset($query_result[0]) ? $query_result[0] :null;
	        if(!is_array($query_result) || empty($query_result))
	        {
	            $result = self::return_desc('1',"未查询到上游cp对的片源信息,消息未反馈给上游");
	            nn_log::write_log_message(LOG_MODEL_BK_CDN_NOTIFY,"消息反馈上游播放串结果".var_export($query_result,true), ORG_ID);
	            return $result;
	        }
	        if(isset($query_result['nns_encode_flag']) && $query_result['nns_encode_flag'] == '1')
	        {
	            $sql_by_query_index_import_id = "select * from nns_vod_media WHERE nns_id=(select nns_in_media_id from nns_file_encode where nns_sp_id='{$sql_c2_task['nns_org_id']}' and nns_cp_id='{$query_result['nns_cp_id']}' and nns_out_media_id='{$query_result['nns_id']}') limit 1";
	            $query_result_encode = nl_query_by_db($sql_by_query_index_import_id,$dc->db());
	            $query_result_encode  = isset($query_result_encode[0]) ? $query_result_encode[0] :null;
	            if(!is_array($query_result_encode) || empty($query_result_encode))
	            {
	                $result = self::return_desc('1',"未查询到上游cp对的片源信息,消息未反馈给上游");
	                nn_log::write_log_message(LOG_MODEL_BK_CDN_NOTIFY,"消息反馈上游播放串结果".var_export($query_result_encode,true), ORG_ID);
	                return $query_result_encode;
	            }
	            $query_result = $query_result_encode;
	        }
            if(isset($sp_config['cdn_send_cdi_mode_url']) && strlen($sp_config['cdn_send_cdi_mode_url'])>0 && $c2_notify['nns_notify_PlayId'] == 'bk_placeholder')
            {
                 $result_asset_id_by_sp_id = public_model_exec::get_asset_id_by_sp_id($sql_c2_task['nns_org_id'], 'media', $query_result['nns_id'],$query_result,$sp_config,'cdn');
                 if($result_asset_id_by_sp_id['ret'] !=0 || !isset($result_asset_id_by_sp_id['data_info']) || strlen($result_asset_id_by_sp_id['data_info']) <1)
                 {
                     nn_log::write_log_message(LOG_MODEL_BK_CDN_NOTIFY,"消息反馈上游播放串查询注入CDN的播放ID，结果有误".var_export($result_asset_id_by_sp_id,true), ORG_ID);
                     return $result_asset_id_by_sp_id;
                 }
                 $c2_notify['nns_notify_PlayId'] = $result_asset_id_by_sp_id['data_info'];
            }
            $sql_update_media ="update nns_vod_media set nns_content_id='{$c2_notify['nns_notify_PlayId']}',nns_media_service='{$sp_config['media_service_type']}' where nns_id='{$query_result['nns_id']}'";
            nl_execute_by_db($sql_update_media,$dc->db());
            $query_result['nns_content_id'] = $c2_notify['nns_notify_PlayId'];
            if((strlen($query_result['nns_cp_id']) > 5 && substr($query_result['nns_cp_id'], 0,5) == 'fuse_'))
            {
                $query_result['nns_cp_id'] = substr($query_result['nns_cp_id'], 5);
//                 echo "select * from nns_vod_media where nns_import_id='{$query_result['nns_import_id']}' and nns_cp_id='{$query_result['nns_cp_id']}'";die;
                $result_temp_media = nl_query_by_db("select * from nns_vod_media where nns_import_id='{$query_result['nns_import_id']}' and nns_cp_id='{$query_result['nns_cp_id']}'",$dc->db());
                $result_temp_media = $result_temp_media[0];
                $result_temp_media['nns_content_id'] = $c2_notify['nns_notify_PlayId'];
                $query_result = $result_temp_media;
                $result_c2_task_info = nl_query_by_db("select * from nns_mgtvbk_c2_task where nns_org_id='starcor_make' and nns_ref_id='{$query_result['nns_id']}' and nns_type='media'",$dc->db());
                $result_c2_task_info = $result_c2_task_info[0];
            }
            else
            {
                $result_c2_task_info = nl_query_by_db("select * from nns_mgtvbk_c2_task where nns_id='{$c2_info['nns_task_id']}'",$dc->db());
                $result_c2_task_info = $result_c2_task_info[0];
            }
            $result = self::notify_upstream($query_result,$c2_info['nns_action'],array('ret'=>0),$sp_config,$result_c2_task_info,$dc);
	    }
	    else
	    {
	        $result = self::return_desc('0',"不需要消息反馈给上游");
	    }
	    nn_log::write_log_message(LOG_MODEL_BK_CDN_NOTIFY,"消息反馈上游播放串结果".var_export($result,true), ORG_ID);
	    return $result;
	}
	
	
	/**
	 * 生成路径
	 * @param unknown $c2_info
	 * @return multitype:unknown string
	 */
	static public function make_notify_dir($c2_info)
	{
	    $str_date_file = date('Ymd');
	    $base_file_dir = dirname(dirname(dirname(__FILE__))).'/data/mgtv/'.strtolower($c2_info['nns_org_id']).'/notify/'.strtolower($c2_info['nns_task_type']);
	    $notify_save_path = $base_file_dir.'/'.$str_date_file.'/'.$c2_info['nns_id'].'.xml';
	    $temp_nns_notify_content = $str_date_file.'/'.$c2_info['nns_id'].'.xml';
	    if(file_exists($notify_save_path))
	    {
	        $nns_id = np_guid_rand();
	        $notify_save_path = $base_file_dir.'/'.$str_date_file.'/'.$c2_info['nns_id'].'_'.$nns_id.'.xml';
	        $temp_nns_notify_content = $str_date_file.'/'.$c2_info['nns_id'].'_'.$nns_id.'.xml';
	    }
	    $path_parts = pathinfo($notify_save_path);
	    $data = array(
	        'base_path'=>$temp_nns_notify_content,
	        'full_path'=>$notify_save_path,
	    );
	    $result = true;
	    if (!is_dir($path_parts['dirname']))
	    {
	        $result = mkdir($path_parts['dirname'], 0777, true);
	    }
	    return $result ? self::return_desc(0,'ok',$data) : self::return_desc(1,'create content file dir error',$data);
	}
	
	
	/**
	 * 处理url文件
	 * @param unknown $dc
	 * @param unknown $sp_config
	 * @param unknown $c2_info
	 * @param unknown $c2_notify
	 */
	static public function handle_notify_result_url($dc,$sp_config,$c2_info,$c2_notify)
	{
	    if(strpos($c2_notify['nns_notify_result_url'],'ftp') && strpos($c2_notify['nns_notify_result_url'], 'sftp') === false)
	    {
	        $url_arr = parse_url($c2_notify['nns_notify_result_url']);
	        $port = isset($url_arr["port"]) ? $url_arr["port"] : 21;
	        include_once NPDIR . '/np_ftp.php';
	        $ftp1=new nns_ftp($url_arr['host'],$url_arr["user"],$url_arr["pass"],$port);
	        $ftpcon1=$ftp1->connect();
	        if (empty($ftpcon1))
	        {
	            nn_log::write_log_message(LOG_MODEL_BK_CDN_NOTIFY, "获取远端ftp连接失败:{$c2_notify['nns_notify_result_url']}", ORG_ID);
	            return self::return_desc(1,'ftp connect error');
	        }
	        $result = self::make_notify_dir($c2_info);
	        if($result['ret'] != 0)
	        {
	            nn_log::write_log_message(LOG_MODEL_BK_CDN_NOTIFY, "创建文件夹失败:".var_export($result,true), ORG_ID);
	            return $result;
	        }
	        $result = $result['data_info'];
	        $rs = $ftp1->get($url_arr["path"],$result['full_path']);
	        if($rs==false)
	        {
	            nn_log::write_log_message(LOG_MODEL_BK_CDN_NOTIFY, "下载远程文件[{$c2_notify['nns_notify_result_url']}]到本地文件[{$result['full_path']}]失败", ORG_ID);
	            return self::return_desc(1,'download file error');
	        }
	        $c2_task_log['nns_notify_content'] = $result['base_path'];
	        $nns_notify_content = @file_get_contents($result['full_path']);
	    }
	    else
	    {
	        //curl抓取 远程文件的内容
	        $ch = curl_init();
	        curl_setopt($ch, CURLOPT_URL, $c2_notify['nns_notify_result_url']);
	        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
	        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
	        $nns_notify_content = curl_exec($ch);
	        $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
	        curl_close($ch);
	        //如果内容为空  或者根本没这个xml文件
	        if (empty($nns_notify_content) || !$nns_notify_content || $http_code >= 400)
	        {
	            nn_log::write_log_message(LOG_MODEL_BK_CDN_NOTIFY, "HTTP下载远程文件[{$c2_notify['nns_notify_result_url']}]失败", ORG_ID);
	            return self::return_desc(1,'download file error');
	        }
	        $result = self::make_notify_dir($c2_info);
	        if($result['ret'] != 0)
	        {
	            nn_log::write_log_message(LOG_MODEL_BK_CDN_NOTIFY, "创建文件夹失败:".var_export($result,true), ORG_ID);
	            return $result;
	        }
	        $result = $result['data_info'];
	        $file_put = file_put_contents($result['full_path'], $nns_notify_content);
	        if(!$file_put)
	        {
	            nn_log::write_log_message(LOG_MODEL_BK_CDN_NOTIFY, "HTTP下载远程文件[{$c2_notify['nns_notify_result_url']}]失败", ORG_ID);
	            return self::return_desc(1,'save file error');
	        }
	        $c2_task_log['nns_notify_content'] = $result['base_path'];
	    }
	    nn_log::write_log_message(LOG_MODEL_BK_CDN_NOTIFY, '消息反馈的xml:'.$nns_notify_content, ORG_ID);
	    $flag = true;
	    if(strlen($nns_notify_content) >0 && isset($sp_config['c2_media_notify_mode']) && in_array($sp_config['c2_media_notify_mode'], array('1','2')))
	    {
	        $flag = false;
	        include_once dirname(dirname(dirname(dirname(__FILE__)))).'/np/np_xml2array.class.php';
	        include_once dirname(dirname(dirname(__FILE__))).'/nn_logic/vod_media/vod_media.class.php';
	        //解析下载的XML
	        $dom = new DOMDocument('1.0', 'utf-8');
	        $dom->loadXML($nns_notify_content);
	        $xml = $dom->saveXML();
	        $xml_arr = np_xml2array::getArrayData($xml);
	        if($xml_arr['ret'] !=1)
	        {
	            nn_log::write_log_message(LOG_MODEL_BK_CDN_NOTIFY, "消息反馈的xml解析失败：".var_export($xml_arr,true), ORG_ID);
	            return self::return_desc(1,'xml format error');
	        }
	        $xml_arr = (isset($xml_arr['data']['children'][0]['children'])) ? $xml_arr['data']['children'][0]['children'] : null;
	        if(empty($xml_arr) || !is_array($xml_arr))
	        {
	            nn_log::write_log_message(LOG_MODEL_BK_CDN_NOTIFY, '消息反馈的xml解析成功，但是数组有问题:'.var_export($xml_arr,true), ORG_ID);
	            return self::return_desc(1,'xml format inconformity');
	        }
	        $str_c2_play_url_ip = (isset($sp_config['c2_play_url_ip']) && strlen($sp_config['c2_play_url_ip']) >0) ? trim($sp_config['c2_play_url_ip']) : '';
	        foreach ($xml_arr as $val)
	        {
	            if( !isset($val['children']) || empty($val['children']) || !is_array($val['children'])
	                || !isset($val['attributes']['ContentID']) || strlen($val['attributes']['ContentID']) <1 || !isset($val['attributes']['ElementType']) ||
	                $val['attributes']['ElementType'] != 'Movie' || !isset($val['name']) || strtolower($val['name']) != 'resultinfo')
	            {
	                continue;
	            }
	            $child_val = $val['children'];
	            $temp_child_val = null;
	            foreach ($child_val as $c_key=>$c_val)
	            {
	                if(!isset($c_val['attributes']['Name']))
	                {
	                    continue;
	                }
	                $temp_child_val[$c_val['attributes']['Name']] = isset($c_val['content']) ? $c_val['content'] : '';
	            }
	            if(!isset($temp_child_val['ResultCode']) || $temp_child_val['ResultCode'] !=0 || !isset($temp_child_val['ServiceURL']) || strlen($temp_child_val['ServiceURL']) <1)
	            {
	                continue;
	            }
	            $result_media = nl_vod_media_v2::query_by_id($dc, $val['attributes']['ContentID']);
	            $nns_ext_url = (isset($result_media['data_info']['nns_ext_url']) && strlen($result_media['data_info']['nns_ext_url']) >0) ? json_decode($result_media['data_info']['nns_ext_url'],true) : array();
	            $nns_ext_url = is_array($nns_ext_url) ? $nns_ext_url : array();
	            switch ($sp_config['c2_media_notify_mode'])
	            {
	                case '1':
	                    $flag = true;
	                    if(strlen($str_c2_play_url_ip) >0)
	                    {
	                        $temp_server_url = parse_url($temp_child_val['ServiceURL']);
	                        $temp_child_val['ServiceURL'] = '';
	                        if(isset($temp_server_url['scheme']) && strlen($temp_server_url['scheme'])>0)
	                        {
	                            $temp_child_val['ServiceURL'].=$temp_server_url['scheme']."://";
	                        }
	                        $temp_child_val['ServiceURL'].="{$str_c2_play_url_ip}/";
	                        if(isset($temp_server_url['host']) && strlen($temp_server_url['host'])>0)
	                        {
	                            $temp_child_val['ServiceURL'].=$temp_server_url['host'];
	                        }
	                        if(isset($temp_server_url['port']) && strlen($temp_server_url['port'])>0)
	                        {
	                            $temp_child_val['ServiceURL'].=":".$temp_server_url['port'];
	                        }
	                        if(isset($temp_server_url['path']) && strlen($temp_server_url['path'])>0)
	                        {
	                            $temp_child_val['ServiceURL'].=$temp_server_url['path'];
	                        }
	                        if(isset($temp_server_url['query']) && strlen($temp_server_url['query'])>0)
	                        {
	                            $temp_child_val['ServiceURL'].='?'.$temp_server_url['query'];
	                        }
	                    }
	                    $nns_ext_url['play_url'] = $temp_child_val['ServiceURL'];
	                    break;
	                case '2':
	                    $flag = true;
	                    $nns_ext_url['play_content_id'] = $temp_child_val['ServiceURL'];
	                    break;
	            }
	            if(!$flag)
	            {
	                continue;
	            }
	            $params_media = array(
	                'nns_ext_url' =>json_encode($nns_ext_url),
	                'nns_media_service' =>$sp_config['media_service_type'],
	            );
	            $result_edit_media = nl_vod_media_v2::edit($dc,$params_media, $val['attributes']['ContentID']);
	            if($result_edit_media['ret'] !=0)
	            {
	                nn_log::write_log_message(LOG_MODEL_BK_CDN_NOTIFY, '修改片源信息数据库执行失败:'.var_export($result_edit_media,true), ORG_ID);
	                return self::return_desc(1,'edit media info db error');
	            }
	        }
	    }
	    return $flag ? self::return_desc(0,'ok',$result) : self::return_desc(1,'not hit one media info',$result);
	}
	
	
	/**
	 * 标准消息通知
	 * @param unknown $result_media
	 * @param unknown $action
	 * @param unknown $result
	 * @param unknown $sp_config
	 * @param unknown $result_c2_task_info
	 * @return multitype:number string |Ambigous <Ambigous, object>
	 */
	public static function notify_upstream($result_media,$action,$result,$sp_config,$result_c2_task_info,$dc,$type='media',$sp_id='',$flag = true,$project=null)
	{
	    include_once dirname(dirname(dirname(__FILE__))).'/notify/make_notify_file.class.php';
	    include_once dirname(dirname(dirname(__FILE__))).'/nn_logic/cp/cp.class.php';
	    $result_cp = nl_cp::query_by_id($dc,$result_media['nns_cp_id']);
	    if(!isset($result_cp['data_info']['nns_config']) || strlen($result_cp['data_info']['nns_config'])<1)
	    {
	        return self::_make_return_data(0,"不存在cp配置，直接不反馈上游");
	    }
	    $arr_cp_config = json_decode($result_cp['data_info']['nns_config'],true);
	    if(!isset($arr_cp_config['asyn_feedback_message_enabled']) || $arr_cp_config['asyn_feedback_message_enabled'] !='1')
	    {
	        return self::_make_return_data(0,"cp配置不反馈上游，直接不反馈上游");
	    }
	    if($project === null)
	    {
	        global $g_project_name;
	        $project_name = (isset($g_project_name) && strlen($g_project_name)>0) ? $g_project_name : '';
	    }
	    else
	    {
	        $project_name = $project;
	    }
	    if(strlen($project_name) <1)
	    {
	        return self::_make_return_data(1,"全局项目ID配置为空:[{$project_name}];line:[".__LINE__."];file[".__FILE__."]");
	    }
	    global $g_bk_web_url;
	    $bk_web_url = (isset($g_bk_web_url) && strlen($g_bk_web_url)>0) ? $g_bk_web_url : '';
	    $bk_web_url = rtrim(rtrim(trim($bk_web_url),'/'),'\\');
	    if(strlen($bk_web_url) <1)
	    {
	        return self::_make_return_data(1,"后台基本地址(数据库配置文件父级目录)配置为空:[{$bk_web_url}];line:[".__LINE__."];file[".__FILE__."]");
	    }
	    unset($g_project_name);
	    unset($g_bk_web_url);
	    $result_media['nns_cp_id'] = (strlen($result_media['nns_cp_id']) > 5 && substr($result_media['nns_cp_id'], 0,5) == 'fuse_') ? substr($result_media['nns_cp_id'], 5) : $result_media['nns_cp_id'];
	    $str_object = 'notify';
	    if($flag)
	    {
	        $str_include_file_1 = dirname(dirname(dirname(__FILE__))).'/notify/soap/'.$project_name.'/'.$result_media['nns_cp_id'].'/notify.php';
	        if(!file_exists($str_include_file_1))
	        {
	            $str_include_file = dirname(dirname(dirname(__FILE__))).'/notify/soap/'.$project_name.'/notify.php';
	            if(!file_exists($str_include_file))
	            {
	                return self::_make_return_data(1,"加载消息反馈文件不存在:[{$str_include_file}];line:[".__LINE__."];file[".__FILE__."]");
	            }
	            include_once $str_include_file;
	        }
	        else
	        {
	            include_once $str_include_file_1;
	            $str_object = $result_media['nns_cp_id']."_notify";
	        }
	    }
	    if(($result_media['nns_cp_id'] == 'zhongguangchuanbo' || $result_media['nns_cp_id'] == 'shidake') && $type == 'index')
	    {
	        return self::_make_return_data(0,"ok");
	    }
	    $ResultCode = (isset($result['ret']) && $result['ret'] == 0) ? 0 : -1;
	    $Description = ($ResultCode == 0) ? 'success' : 'error';
	    $obj_make_file = new nl_make_notify_file(ORG_ID,$result_media['nns_cp_id']);
	    #TODO
// 	    $result_media['nns_content_id'] = '1111111';
	    $result_notify_file = $obj_make_file->make_notify_file($result_media,$ResultCode,$Description,$type,$action,null,$sp_id);	    
        
	    if($result_notify_file['ret'] !=0)
	    {
	        return $result_notify_file;
	    }
	    $site_callback_url = rtrim(rtrim(trim($sp_config['site_callback_url']),'/'),'\\');
	    if(strlen($site_callback_url) <1)
	    {
	        return self::_make_return_data(1,"消息反馈上游地址为空:[{$site_callback_url}];line:[".__LINE__."];file[".__FILE__."]");
	    }
	    $str_include_file_server = dirname(dirname(dirname(__FILE__))).'/notify/soap/'.$project_name.'/'.$result_media['nns_cp_id'].'/service.php';
	    if(!file_exists($str_include_file_server))
	    {
	        return self::_make_return_data(0,"消息反馈上游地址为空消息可以不反馈文件,或者文件未配置;地址[{$str_include_file_server}]");
	    }
	    $WDSL_URL = $bk_web_url.'/notify/soap/'.$project_name.'/'.$result_media['nns_cp_id'].'/service.php?wsdl';
	    nn_log::write_log_message(LOG_MODEL_BK_CDN_NOTIFY,"消息反馈上游结果[{$result_c2_task_info['nns_message_id']}][{$result_media['nns_cp_id']}][{$site_callback_url}{$result_notify_file['data_info']}]", ORG_ID);
        
	    if($result_media['nns_cp_id'] == 'CSKJ')
	    {
	        $obj_soap = new $str_object($WDSL_URL,$result_media['nns_cp_id'],'starcor',$result_c2_task_info['nns_message_id'],(int)$ResultCode,$Description,$site_callback_url.$result_notify_file['data_info']);
	    }
	    else if($result_media['nns_cp_id'] == 'zhongguangchuanbo' || $result_media['nns_cp_id'] == 'shidake')
	    {
	        $obj_soap = new $str_object($WDSL_URL,$result_media['nns_cp_id'],'starcor',$result_c2_task_info['nns_message_id'],(int)$ResultCode,$Description,$site_callback_url.$result_notify_file['data_info']);
	    }
	    else
	    {
	       $obj_soap = new $str_object($WDSL_URL,$result_media['nns_cp_id'],'starcor',$result_c2_task_info['nns_message_id'],(int)$ResultCode,$Description,$site_callback_url.$result_notify_file['data_info']);
	    }
	    $soap_result = $obj_soap->ExecCmd();
	    
	    if(isset($soap_result->ResultCode))
	    {
	        $ResultCode = ($soap_result->ResultCode == 0) ? 0 : 1;
	    }
	    else
	    {
	        $ResultCode = ($soap_result->Result == 0) ? 0 : 1;
	    }
	    return self::_make_return_data($ResultCode,isset($soap_result->ErrorDescription) ? $soap_result->ErrorDescription."消息ID[{$result_c2_task_info['nns_message_id']}];消息存放地址[{$site_callback_url}{$result_notify_file['data_info']}]" : '');
	}
	
	
	/**
	 * 新疆福富消息通知
	 * @param unknown $result_media
	 * @param unknown $action
	 * @param unknown $result
	 * @param unknown $sp_config
	 * @param unknown $result_c2_task_info
	 * @return multitype:number string |Ambigous <Ambigous, object>
	 */
	public static function notify_upstream_third($task_id,$sp_config,$obj_dc,$task_log_id)
	{
	    global $g_project_name;
	    $project_name = (isset($g_project_name) && strlen($g_project_name)>0) ? $g_project_name : '';
	    if(strlen($project_name) <1)
	    {
	        return self::_make_return_data(1,"全局项目ID配置为空:[{$project_name}];line:[".__LINE__."];file[".__FILE__."]");
	    }
	    $str_include_file = dirname(dirname(dirname(__FILE__))).'/notify/soap/'.$g_project_name.'/make_ff_notify_file.class.php';
	    if(!file_exists($str_include_file))
	    {
	        return self::_make_return_data(1,"文件组装类不存在:[{$str_include_file}];line:[".__LINE__."];file[".__FILE__."]");
	    }
	    include_once $str_include_file;
	    global $g_bk_web_url;
	    $bk_web_url = (isset($g_bk_web_url) && strlen($g_bk_web_url)>0) ? $g_bk_web_url : '';
	    $bk_web_url = rtrim(rtrim(trim($bk_web_url),'/'),'\\');
	    if(strlen($bk_web_url) <1)
	    {
	        return self::_make_return_data(1,"后台基本地址(数据库配置文件父级目录)配置为空:[{$bk_web_url}];line:[".__LINE__."];file[".__FILE__."]");
	    }
	    unset($g_project_name);
	    unset($g_bk_web_url);
	    $str_include_file = dirname(dirname(dirname(__FILE__))).'/notify/soap/'.$project_name.'/notify.php';
	    if(!file_exists($str_include_file))
	    {
	        return self::_make_return_data(1,"加载消息反馈文件不存在:[{$str_include_file}];line:[".__LINE__."];file[".__FILE__."]");
	    }
	    include_once $str_include_file;
	    $obj_make_file = new nl_make_ff_notify_file('starcor',$sp_config['cdn_notify_third_party_mark'],$obj_dc,$sp_config);
	    $result_init = $obj_make_file->init($task_id);
	    if($result_init['ret'] !=0 || !isset($result_init['data_info']) || strlen($result_init['data_info']) <1)
	    {
	        return $result_init;
	    }
	    $site_callback_url = rtrim(rtrim(trim($sp_config['site_callback_url']),'/'),'\\');
	    if(strlen($site_callback_url) <1)
	    {
	        return self::_make_return_data(1,"消息反馈上游地址为空:[{$site_callback_url}];line:[".__LINE__."];file[".__FILE__."]");
	    }
	    $str_include_file_server = dirname(dirname(dirname(__FILE__))).'/notify/soap/'.$project_name.'/'.$sp_config['cdn_notify_third_party_mark'].'/service.php';
	    if(!file_exists($str_include_file_server))
	    {
	        return self::_make_return_data(1,"消息反馈上游地址为空消息可以不反馈文件,或者文件未配置;地址[{$str_include_file_server}]");
	    }
	    $WDSL_URL = $bk_web_url.'/notify/soap/'.$project_name.'/'.$sp_config['cdn_notify_third_party_mark'].'/service.php?wsdl';
	    $obj_soap = new ff_notify($WDSL_URL,'starcor',$sp_config['cdn_notify_third_party_mark'],md5($task_log_id),$site_callback_url.$result_init['data_info']);

	    $arr_config  = array(
	        'ftp_url'=>$site_callback_url.$result_init['data_info'],
	        'log_id'=>$task_log_id,
	        'md5_log_id'=>md5($task_log_id),
	        'cdn_notify_third_party_mark'=>$sp_config['cdn_notify_third_party_mark'],
	    );
	    
	    $soap_result = $obj_soap->ExecCmd();
	    $ResultCode = ($soap_result->result == 0) ? 0 : 1;
	    return self::_make_return_data($ResultCode,isset($soap_result->ErrorDescription) ? $soap_result->ErrorDescription."消息ID[{$task_log_id}];消息存放地址[{$site_callback_url}{$result_init['data_info']}]参数:".var_export($arr_config,true) : "消息ID[{$task_log_id}];消息存放地址[{$site_callback_url}{$result_init['data_info']}]参数:".var_export($arr_config,true));
	}
	
	

	static public function _make_return_data($ret=1,$reason='error',$data=null)
	{
		return array(
				'ret'=>$ret,
				'reason'=>$reason,
				'data_info'=>$data,
		);
	}
	
	static public function _save_img_from_url($img_file,$img_url){
		$ret_data = array();
		$json_data = null;
		$http_code = null;
		for ($i = 0; $i < 3; $i++) {
				$http_client = new np_http_curl_class();
				$json_data = $http_client->get($img_url);
				$http_code = $http_client->curl_getinfo['http_code'];
				if ($http_code != 200) {
						//i_echo('-----下载失败:'.$img_url);
						continue;
				} else {
						break;
				}
		}
		if ($json_data && $http_code && $http_code == 200) {
			  return  file_put_contents($img_file,$json_data);
		}
		return false;
	}
	
	static public function update_notify_content($nns_id,$nns_notify_content){
		$db = nn_get_db(NL_DB_WRITE);
		$sql = "update nns_mgtvbk_c2_log set nns_notify_content='".$nns_notify_content."' where nns_id='".$nns_id."'";
		return nl_execute_by_db($sql,$db);
	}

	static public function get_c2_log_list($sp_id,$filter=null,$start=0,$size=100){
		$db = nn_get_db(NL_DB_READ);
		//$db->open();
		$sql = "select  * from nns_mgtvbk_c2_log where nns_org_id='".$sp_id."' ";
		$sql_count = "select  count(*) from nns_mgtvbk_c2_log where nns_org_id='".$sp_id."' ";
		if($filter != null){
			$wh_arr = array();
			if(!empty($filter['nns_task_name'])){
				$wh_arr[] = " nns_task_name like '%".$filter['nns_task_name']."%'";
			}
			if(!empty($filter['nns_id'])){
				$wh_arr[] = " nns_id='".$filter['nns_id']."'";
			}
			if(!empty($filter['nns_task_type'])){
				$wh_arr[] = " nns_task_type='".$filter['nns_task_type']."'";
			}
			if(!empty($filter['nns_action'])){
				$wh_arr[] = " nns_action='".$filter['nns_action']."'";
			}

			if(!empty($filter['day_picker_start'])){
				$wh_arr[] = " nns_create_time >='".$filter['day_picker_start']."' ";
			}
			if(!empty($filter['day_picker_end'])){
				$wh_arr[] = " nns_create_time <='".$filter['day_picker_end']."' ";
			}
			if(!empty($filter['notify_time_start'])){
				$wh_arr[] = "  nns_notify_time >='".$filter['notify_time_start']."'";
			}
			if(!empty($filter['notify_time_end'])){
				$wh_arr[] = "  nns_notify_time <='".$filter['notify_time_end']."'";
			}
			if(strlen($filter['nns_cdn_send_time'])>0)
			{
			   $wh_arr[] = " nns_cdn_send_time ='".$filter['nns_cdn_send_time']."'";
			}
			if(!empty($filter['nns_result'])){
			    if($filter['nns_result'] == '[0]')
			    {
			        $wh_arr[] = " nns_result like '[0]%'";
			    }
			    else
			    {
			        $wh_arr[] = " nns_result not like '[0]%'";
			    }
			}
			if(!empty($filter['nns_state'])){
				$state = $filter['nns_state'];
				switch($state){
					case 'request_state_succ':
					$wh_arr[] = " nns_result like '[0]%'";
					break;
					case 'request_state_fail':
					$wh_arr[] = " nns_result like '[-1]%'";
					break;
					case 'notify_state_wait':
					$wh_arr[] = " nns_notify_result='5' ";
					break;
					case 'notify_state_succ':
					$wh_arr[] = " nns_notify_result='0'";
					break;
					case 'notify_state_fail':
					$wh_arr[] = " nns_notify_result='-1'";
					break;
					case 'resend_fail':
					$wh_arr[] = " nns_again=-1";
					break;
				}
				
			}	
			if(!empty($wh_arr))	$sql .= " and ".implode(" and ",$wh_arr);
			if(!empty($wh_arr))	$sql_count .= " and ".implode(" and ",$wh_arr);
		}
		$sql .= " order by nns_create_time desc ";
		$sql .= " limit $start,$size";
		$data = nl_db_get_all($sql,$db);
		$rows = nl_db_get_col($sql_count,$db);
		return array('data'=>$data,'rows'=>$rows);
	}

	static public function delete_c2($ids=array()){
		$db = nn_get_db(NL_DB_WRITE);
		$db_r = nn_get_db(NL_DB_READ);
		$sql = "select nns_task_name from nns_mgtvbk_c2_log where ".nl_db_in($ids,'nns_id');
		$c2_info = nl_db_get_all($sql,$db_r);				
		$sql = "delete from nns_mgtvbk_c2_log where ".nl_db_in($ids,'nns_id');
		return nl_execute_by_db($sql,$db);
	}

	static  public function check_ftp_file($url,$sp_config){
		$url_arr = parse_url($url);
		if(isset($sp_config['cdn_check_ts_accord_address']) && !empty($sp_config['cdn_check_ts_accord_address']))
		{
			$url_arr = parse_url($sp_config['cdn_check_ts_accord_address']);
		}
		$port = isset($url_arr["port"]) ? $url_arr["port"] : 21;
		$time = 10;
		$connect_no=ftp_connect($url_arr['host'],$port,$time);
		if ($connect_no===FALSE) return self::return_desc(1,'ftp连接失败');
		
		@ftp_login(
		$connect_no,
		$url_arr["user"],
		$url_arr["pass"]
		);
		//吉林联通要开启被动模式
		//重庆有线内网检测地址和华为下载地址不一致
		if(empty($sp_config['cdn_check_ts_accord_address']))
		{
			@ftp_pasv($connect_no,true);
		}
		//获取目录
		$path = str_replace("//","/",$url_arr['path']);
		$path_arr = explode("/",$path);
		array_pop($path_arr);
		$url_arr['path'] = implode("/",$path_arr);
		
		$check_int = 1;
		for ($i=1;$i<=3;$i++)
		{
			$contents = @ftp_nlist($connect_no, $url_arr['path']);
			if($contents===false)
			{
				continue;			
			}
			else
			{		
				$check_int = 2;
				//判断文件列表中是否有该文件<author:feijian.gao date:2017-1-19 11:18:13> --->start
				if(is_array($contents) && !empty($contents))
				{
					$check_int = 3;	
					break;
				}
				continue;			
				//--->end
			}
		}
		unset($connect_no);
		if($check_int === 1)
		{
			return self::return_desc(3,'获取文件列表失败');
		}
		elseif ($check_int === 2)
		{
			return self::return_desc(2,'文件不存在');
		}
		else 
		{
			return self::return_desc(0,'文件存在');
		}
	}

	public static function return_desc($ret, $desc=null,$data_info=null)
	{
		$arr_return = array(
			'ret' => $ret,
			'reason' => $desc,
		);
		if($data_info !== null)
		{
		    $arr_return['data_info'] = $data_info;
		}
		return $arr_return;
	}
}
